merged master
[lhc/web/wiklou.git] / languages / Language.php
1 <?php
2 /**
3 * Internationalisation code
4 *
5 * @file
6 * @ingroup Language
7 */
8
9 /**
10 * @defgroup Language Language
11 */
12
13 if ( !defined( 'MEDIAWIKI' ) ) {
14 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
15 exit( 1 );
16 }
17
18 # Read language names
19 global $wgLanguageNames;
20 require_once( dirname( __FILE__ ) . '/Names.php' );
21
22 if ( function_exists( 'mb_strtoupper' ) ) {
23 mb_internal_encoding( 'UTF-8' );
24 }
25
26 /**
27 * a fake language converter
28 *
29 * @ingroup Language
30 */
31 class FakeConverter {
32
33 /**
34 * @var Language
35 */
36 var $mLang;
37 function __construct( $langobj ) { $this->mLang = $langobj; }
38 function autoConvertToAllVariants( $text ) { return array( $this->mLang->getCode() => $text ); }
39 function convert( $t ) { return $t; }
40 function convertTo( $text, $variant ) { return $text; }
41 function convertTitle( $t ) { return $t->getPrefixedText(); }
42 function getVariants() { return array( $this->mLang->getCode() ); }
43 function getPreferredVariant() { return $this->mLang->getCode(); }
44 function getDefaultVariant() { return $this->mLang->getCode(); }
45 function getURLVariant() { return ''; }
46 function getConvRuleTitle() { return false; }
47 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
48 function getExtraHashOptions() { return ''; }
49 function getParsedTitle() { return ''; }
50 function markNoConversion( $text, $noParse = false ) { return $text; }
51 function convertCategoryKey( $key ) { return $key; }
52 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
53 function armourMath( $text ) { return $text; }
54 }
55
56 /**
57 * Internationalisation code
58 * @ingroup Language
59 */
60 class Language {
61
62 /**
63 * @var LanguageConverter
64 */
65 var $mConverter;
66
67 var $mVariants, $mCode, $mLoaded = false;
68 var $mMagicExtensions = array(), $mMagicHookDone = false;
69 private $mHtmlCode = null;
70
71 var $dateFormatStrings = array();
72 var $mExtendedSpecialPageAliases;
73
74 protected $namespaceNames, $mNamespaceIds, $namespaceAliases;
75
76 /**
77 * ReplacementArray object caches
78 */
79 var $transformData = array();
80
81 /**
82 * @var LocalisationCache
83 */
84 static public $dataCache;
85
86 static public $mLangObjCache = array();
87
88 static public $mWeekdayMsgs = array(
89 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
90 'friday', 'saturday'
91 );
92
93 static public $mWeekdayAbbrevMsgs = array(
94 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
95 );
96
97 static public $mMonthMsgs = array(
98 'january', 'february', 'march', 'april', 'may_long', 'june',
99 'july', 'august', 'september', 'october', 'november',
100 'december'
101 );
102 static public $mMonthGenMsgs = array(
103 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
104 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
105 'december-gen'
106 );
107 static public $mMonthAbbrevMsgs = array(
108 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
109 'sep', 'oct', 'nov', 'dec'
110 );
111
112 static public $mIranianCalendarMonthMsgs = array(
113 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
114 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
115 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
116 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
117 );
118
119 static public $mHebrewCalendarMonthMsgs = array(
120 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
121 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
122 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
123 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
124 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
125 );
126
127 static public $mHebrewCalendarMonthGenMsgs = array(
128 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
129 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
130 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
131 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
132 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
133 );
134
135 static public $mHijriCalendarMonthMsgs = array(
136 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
137 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
138 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
139 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
140 );
141
142 /**
143 * @since 1.20
144 * @var array
145 */
146 static public $durationIntervals = array(
147 'millennia' => 31557600000,
148 'centuries' => 3155760000,
149 'decades' => 315576000,
150 'years' => 31557600, // 86400 * 365.25
151 'weeks' => 604800,
152 'days' => 86400,
153 'hours' => 3600,
154 'minutes' => 60,
155 'seconds' => 1,
156 );
157
158 /**
159 * Get a cached language object for a given language code
160 * @param $code String
161 * @return Language
162 */
163 static function factory( $code ) {
164 if ( !isset( self::$mLangObjCache[$code] ) ) {
165 if ( count( self::$mLangObjCache ) > 10 ) {
166 // Don't keep a billion objects around, that's stupid.
167 self::$mLangObjCache = array();
168 }
169 self::$mLangObjCache[$code] = self::newFromCode( $code );
170 }
171 return self::$mLangObjCache[$code];
172 }
173
174 /**
175 * Create a language object for a given language code
176 * @param $code String
177 * @throws MWException
178 * @return Language
179 */
180 protected static function newFromCode( $code ) {
181 // Protect against path traversal below
182 if ( !Language::isValidCode( $code )
183 || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
184 {
185 throw new MWException( "Invalid language code \"$code\"" );
186 }
187
188 if ( !Language::isValidBuiltInCode( $code ) ) {
189 // It's not possible to customise this code with class files, so
190 // just return a Language object. This is to support uselang= hacks.
191 $lang = new Language;
192 $lang->setCode( $code );
193 return $lang;
194 }
195
196 // Check if there is a language class for the code
197 $class = self::classFromCode( $code );
198 self::preloadLanguageClass( $class );
199 if ( MWInit::classExists( $class ) ) {
200 $lang = new $class;
201 return $lang;
202 }
203
204 // Keep trying the fallback list until we find an existing class
205 $fallbacks = Language::getFallbacksFor( $code );
206 foreach ( $fallbacks as $fallbackCode ) {
207 if ( !Language::isValidBuiltInCode( $fallbackCode ) ) {
208 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
209 }
210
211 $class = self::classFromCode( $fallbackCode );
212 self::preloadLanguageClass( $class );
213 if ( MWInit::classExists( $class ) ) {
214 $lang = Language::newFromCode( $fallbackCode );
215 $lang->setCode( $code );
216 return $lang;
217 }
218 }
219
220 throw new MWException( "Invalid fallback sequence for language '$code'" );
221 }
222
223 /**
224 * Returns true if a language code string is of a valid form, whether or
225 * not it exists. This includes codes which are used solely for
226 * customisation via the MediaWiki namespace.
227 *
228 * @param $code string
229 *
230 * @return bool
231 */
232 public static function isValidCode( $code ) {
233 return
234 strcspn( $code, ":/\\\000" ) === strlen( $code )
235 && !preg_match( Title::getTitleInvalidRegex(), $code );
236 }
237
238 /**
239 * Returns true if a language code is of a valid form for the purposes of
240 * internal customisation of MediaWiki, via Messages*.php.
241 *
242 * @param $code string
243 *
244 * @since 1.18
245 * @return bool
246 */
247 public static function isValidBuiltInCode( $code ) {
248
249 if( !is_string($code) ) {
250 $type = gettype( $code );
251 if( $type === 'object' ) {
252 $addmsg = " of class " . get_class( $code );
253 } else {
254 $addmsg = '';
255 }
256 throw new MWException( __METHOD__ . " must be passed a string, $type given$addmsg" );
257 }
258
259 return preg_match( '/^[a-z0-9-]+$/i', $code );
260 }
261
262 /**
263 * @param $code
264 * @return String Name of the language class
265 */
266 public static function classFromCode( $code ) {
267 if ( $code == 'en' ) {
268 return 'Language';
269 } else {
270 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
271 }
272 }
273
274 /**
275 * Includes language class files
276 *
277 * @param $class string Name of the language class
278 */
279 public static function preloadLanguageClass( $class ) {
280 global $IP;
281
282 if ( $class === 'Language' ) {
283 return;
284 }
285
286 if ( !defined( 'MW_COMPILED' ) ) {
287 // Preload base classes to work around APC/PHP5 bug
288 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
289 include_once( "$IP/languages/classes/$class.deps.php" );
290 }
291 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
292 include_once( "$IP/languages/classes/$class.php" );
293 }
294 }
295 }
296
297 /**
298 * Get the LocalisationCache instance
299 *
300 * @return LocalisationCache
301 */
302 public static function getLocalisationCache() {
303 if ( is_null( self::$dataCache ) ) {
304 global $wgLocalisationCacheConf;
305 $class = $wgLocalisationCacheConf['class'];
306 self::$dataCache = new $class( $wgLocalisationCacheConf );
307 }
308 return self::$dataCache;
309 }
310
311 function __construct() {
312 $this->mConverter = new FakeConverter( $this );
313 // Set the code to the name of the descendant
314 if ( get_class( $this ) == 'Language' ) {
315 $this->mCode = 'en';
316 } else {
317 $this->mCode = str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
318 }
319 self::getLocalisationCache();
320 }
321
322 /**
323 * Reduce memory usage
324 */
325 function __destruct() {
326 foreach ( $this as $name => $value ) {
327 unset( $this->$name );
328 }
329 }
330
331 /**
332 * Hook which will be called if this is the content language.
333 * Descendants can use this to register hook functions or modify globals
334 */
335 function initContLang() { }
336
337 /**
338 * Same as getFallbacksFor for current language.
339 * @return array|bool
340 * @deprecated in 1.19
341 */
342 function getFallbackLanguageCode() {
343 wfDeprecated( __METHOD__ );
344 return self::getFallbackFor( $this->mCode );
345 }
346
347 /**
348 * @return array
349 * @since 1.19
350 */
351 function getFallbackLanguages() {
352 return self::getFallbacksFor( $this->mCode );
353 }
354
355 /**
356 * Exports $wgBookstoreListEn
357 * @return array
358 */
359 function getBookstoreList() {
360 return self::$dataCache->getItem( $this->mCode, 'bookstoreList' );
361 }
362
363 /**
364 * @return array
365 */
366 public function getNamespaces() {
367 if ( is_null( $this->namespaceNames ) ) {
368 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
369
370 $this->namespaceNames = self::$dataCache->getItem( $this->mCode, 'namespaceNames' );
371 $validNamespaces = MWNamespace::getCanonicalNamespaces();
372
373 $this->namespaceNames = $wgExtraNamespaces + $this->namespaceNames + $validNamespaces;
374
375 $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
376 if ( $wgMetaNamespaceTalk ) {
377 $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
378 } else {
379 $talk = $this->namespaceNames[NS_PROJECT_TALK];
380 $this->namespaceNames[NS_PROJECT_TALK] =
381 $this->fixVariableInNamespace( $talk );
382 }
383
384 # Sometimes a language will be localised but not actually exist on this wiki.
385 foreach ( $this->namespaceNames as $key => $text ) {
386 if ( !isset( $validNamespaces[$key] ) ) {
387 unset( $this->namespaceNames[$key] );
388 }
389 }
390
391 # The above mixing may leave namespaces out of canonical order.
392 # Re-order by namespace ID number...
393 ksort( $this->namespaceNames );
394
395 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames ) );
396 }
397 return $this->namespaceNames;
398 }
399
400 /**
401 * Arbitrarily set all of the namespace names at once. Mainly used for testing
402 * @param $namespaces Array of namespaces (id => name)
403 */
404 public function setNamespaces( array $namespaces ) {
405 $this->namespaceNames = $namespaces;
406 $this->mNamespaceIds = null;
407 }
408
409 /**
410 * Resets all of the namespace caches. Mainly used for testing
411 */
412 public function resetNamespaces( ) {
413 $this->namespaceNames = null;
414 $this->mNamespaceIds = null;
415 $this->namespaceAliases = null;
416 }
417
418 /**
419 * A convenience function that returns the same thing as
420 * getNamespaces() except with the array values changed to ' '
421 * where it found '_', useful for producing output to be displayed
422 * e.g. in <select> forms.
423 *
424 * @return array
425 */
426 function getFormattedNamespaces() {
427 $ns = $this->getNamespaces();
428 foreach ( $ns as $k => $v ) {
429 $ns[$k] = strtr( $v, '_', ' ' );
430 }
431 return $ns;
432 }
433
434 /**
435 * Get a namespace value by key
436 * <code>
437 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
438 * echo $mw_ns; // prints 'MediaWiki'
439 * </code>
440 *
441 * @param $index Int: the array key of the namespace to return
442 * @return mixed, string if the namespace value exists, otherwise false
443 */
444 function getNsText( $index ) {
445 $ns = $this->getNamespaces();
446 return isset( $ns[$index] ) ? $ns[$index] : false;
447 }
448
449 /**
450 * A convenience function that returns the same thing as
451 * getNsText() except with '_' changed to ' ', useful for
452 * producing output.
453 *
454 * @param $index string
455 *
456 * @return array
457 */
458 function getFormattedNsText( $index ) {
459 $ns = $this->getNsText( $index );
460 return strtr( $ns, '_', ' ' );
461 }
462
463 /**
464 * Returns gender-dependent namespace alias if available.
465 * @param $index Int: namespace index
466 * @param $gender String: gender key (male, female... )
467 * @return String
468 * @since 1.18
469 */
470 function getGenderNsText( $index, $gender ) {
471 global $wgExtraGenderNamespaces;
472
473 $ns = $wgExtraGenderNamespaces + self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
474 return isset( $ns[$index][$gender] ) ? $ns[$index][$gender] : $this->getNsText( $index );
475 }
476
477 /**
478 * Whether this language makes distinguishes genders for example in
479 * namespaces.
480 * @return bool
481 * @since 1.18
482 */
483 function needsGenderDistinction() {
484 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
485 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
486 // $wgExtraGenderNamespaces overrides everything
487 return true;
488 } elseif ( isset( $wgExtraNamespaces[NS_USER] ) && isset( $wgExtraNamespaces[NS_USER_TALK] ) ) {
489 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
490 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
491 return false;
492 } else {
493 // Check what is in i18n files
494 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
495 return count( $aliases ) > 0;
496 }
497 }
498
499 /**
500 * Get a namespace key by value, case insensitive.
501 * Only matches namespace names for the current language, not the
502 * canonical ones defined in Namespace.php.
503 *
504 * @param $text String
505 * @return mixed An integer if $text is a valid value otherwise false
506 */
507 function getLocalNsIndex( $text ) {
508 $lctext = $this->lc( $text );
509 $ids = $this->getNamespaceIds();
510 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
511 }
512
513 /**
514 * @return array
515 */
516 function getNamespaceAliases() {
517 if ( is_null( $this->namespaceAliases ) ) {
518 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceAliases' );
519 if ( !$aliases ) {
520 $aliases = array();
521 } else {
522 foreach ( $aliases as $name => $index ) {
523 if ( $index === NS_PROJECT_TALK ) {
524 unset( $aliases[$name] );
525 $name = $this->fixVariableInNamespace( $name );
526 $aliases[$name] = $index;
527 }
528 }
529 }
530
531 global $wgExtraGenderNamespaces;
532 $genders = $wgExtraGenderNamespaces + (array)self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
533 foreach ( $genders as $index => $forms ) {
534 foreach ( $forms as $alias ) {
535 $aliases[$alias] = $index;
536 }
537 }
538
539 $this->namespaceAliases = $aliases;
540 }
541 return $this->namespaceAliases;
542 }
543
544 /**
545 * @return array
546 */
547 function getNamespaceIds() {
548 if ( is_null( $this->mNamespaceIds ) ) {
549 global $wgNamespaceAliases;
550 # Put namespace names and aliases into a hashtable.
551 # If this is too slow, then we should arrange it so that it is done
552 # before caching. The catch is that at pre-cache time, the above
553 # class-specific fixup hasn't been done.
554 $this->mNamespaceIds = array();
555 foreach ( $this->getNamespaces() as $index => $name ) {
556 $this->mNamespaceIds[$this->lc( $name )] = $index;
557 }
558 foreach ( $this->getNamespaceAliases() as $name => $index ) {
559 $this->mNamespaceIds[$this->lc( $name )] = $index;
560 }
561 if ( $wgNamespaceAliases ) {
562 foreach ( $wgNamespaceAliases as $name => $index ) {
563 $this->mNamespaceIds[$this->lc( $name )] = $index;
564 }
565 }
566 }
567 return $this->mNamespaceIds;
568 }
569
570 /**
571 * Get a namespace key by value, case insensitive. Canonical namespace
572 * names override custom ones defined for the current language.
573 *
574 * @param $text String
575 * @return mixed An integer if $text is a valid value otherwise false
576 */
577 function getNsIndex( $text ) {
578 $lctext = $this->lc( $text );
579 $ns = MWNamespace::getCanonicalIndex( $lctext );
580 if ( $ns !== null ) {
581 return $ns;
582 }
583 $ids = $this->getNamespaceIds();
584 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
585 }
586
587 /**
588 * short names for language variants used for language conversion links.
589 *
590 * @param $code String
591 * @param $usemsg bool Use the "variantname-xyz" message if it exists
592 * @return string
593 */
594 function getVariantname( $code, $usemsg = true ) {
595 $msg = "variantname-$code";
596 if ( $usemsg && wfMessage( $msg )->exists() ) {
597 return $this->getMessageFromDB( $msg );
598 }
599 $name = self::fetchLanguageName( $code );
600 if ( $name ) {
601 return $name; # if it's defined as a language name, show that
602 } else {
603 # otherwise, output the language code
604 return $code;
605 }
606 }
607
608 /**
609 * @param $name string
610 * @return string
611 */
612 function specialPage( $name ) {
613 $aliases = $this->getSpecialPageAliases();
614 if ( isset( $aliases[$name][0] ) ) {
615 $name = $aliases[$name][0];
616 }
617 return $this->getNsText( NS_SPECIAL ) . ':' . $name;
618 }
619
620 /**
621 * @return array
622 */
623 function getQuickbarSettings() {
624 return array(
625 $this->getMessage( 'qbsettings-none' ),
626 $this->getMessage( 'qbsettings-fixedleft' ),
627 $this->getMessage( 'qbsettings-fixedright' ),
628 $this->getMessage( 'qbsettings-floatingleft' ),
629 $this->getMessage( 'qbsettings-floatingright' ),
630 $this->getMessage( 'qbsettings-directionality' )
631 );
632 }
633
634 /**
635 * @return array
636 */
637 function getDatePreferences() {
638 return self::$dataCache->getItem( $this->mCode, 'datePreferences' );
639 }
640
641 /**
642 * @return array
643 */
644 function getDateFormats() {
645 return self::$dataCache->getItem( $this->mCode, 'dateFormats' );
646 }
647
648 /**
649 * @return array|string
650 */
651 function getDefaultDateFormat() {
652 $df = self::$dataCache->getItem( $this->mCode, 'defaultDateFormat' );
653 if ( $df === 'dmy or mdy' ) {
654 global $wgAmericanDates;
655 return $wgAmericanDates ? 'mdy' : 'dmy';
656 } else {
657 return $df;
658 }
659 }
660
661 /**
662 * @return array
663 */
664 function getDatePreferenceMigrationMap() {
665 return self::$dataCache->getItem( $this->mCode, 'datePreferenceMigrationMap' );
666 }
667
668 /**
669 * @param $image
670 * @return array|null
671 */
672 function getImageFile( $image ) {
673 return self::$dataCache->getSubitem( $this->mCode, 'imageFiles', $image );
674 }
675
676 /**
677 * @return array
678 */
679 function getExtraUserToggles() {
680 return (array)self::$dataCache->getItem( $this->mCode, 'extraUserToggles' );
681 }
682
683 /**
684 * @param $tog
685 * @return string
686 */
687 function getUserToggle( $tog ) {
688 return $this->getMessageFromDB( "tog-$tog" );
689 }
690
691 /**
692 * Get native language names, indexed by code.
693 * Only those defined in MediaWiki, no other data like CLDR.
694 * If $customisedOnly is true, only returns codes with a messages file
695 *
696 * @param $customisedOnly bool
697 *
698 * @return array
699 * @deprecated in 1.20, use fetchLanguageNames()
700 */
701 public static function getLanguageNames( $customisedOnly = false ) {
702 return self::fetchLanguageNames( null, $customisedOnly ? 'mwfile' : 'mw' );
703 }
704
705 /**
706 * Get translated language names. This is done on best effort and
707 * by default this is exactly the same as Language::getLanguageNames.
708 * The CLDR extension provides translated names.
709 * @param $code String Language code.
710 * @return Array language code => language name
711 * @since 1.18.0
712 * @deprecated in 1.20, use fetchLanguageNames()
713 */
714 public static function getTranslatedLanguageNames( $code ) {
715 return self::fetchLanguageNames( $code, 'all' );
716 }
717
718 /**
719 * Get an array of language names, indexed by code.
720 * @param $inLanguage null|string: Code of language in which to return the names
721 * Use null for autonyms (native names)
722 * @param $include string:
723 * 'all' all available languages
724 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
725 * 'mwfile' only if the language is in 'mw' *and* has a message file
726 * @return array: language code => language name
727 * @since 1.20
728 */
729 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
730 global $wgExtraLanguageNames;
731 static $coreLanguageNames;
732
733 if ( $coreLanguageNames === null ) {
734 include( MWInit::compiledPath( 'languages/Names.php' ) );
735 }
736
737 $names = array();
738
739 if( $inLanguage ) {
740 # TODO: also include when $inLanguage is null, when this code is more efficient
741 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
742 }
743
744 $mwNames = $wgExtraLanguageNames + $coreLanguageNames;
745 foreach ( $mwNames as $mwCode => $mwName ) {
746 # - Prefer own MediaWiki native name when not using the hook
747 # TODO: prefer it always to make it consistent, but casing is different in CLDR
748 # - For other names just add if not added through the hook
749 if ( ( $mwCode === $inLanguage && !$inLanguage ) || !isset( $names[$mwCode] ) ) {
750 $names[$mwCode] = $mwName;
751 }
752 }
753
754 if ( $include === 'all' ) {
755 return $names;
756 }
757
758 $returnMw = array();
759 $coreCodes = array_keys( $mwNames );
760 foreach( $coreCodes as $coreCode ) {
761 $returnMw[$coreCode] = $names[$coreCode];
762 }
763
764 if( $include === 'mwfile' ) {
765 $namesMwFile = array();
766 # We do this using a foreach over the codes instead of a directory
767 # loop so that messages files in extensions will work correctly.
768 foreach ( $returnMw as $code => $value ) {
769 if ( is_readable( self::getMessagesFileName( $code ) ) ) {
770 $namesMwFile[$code] = $names[$code];
771 }
772 }
773 return $namesMwFile;
774 }
775 # 'mw' option; default if it's not one of the other two options (all/mwfile)
776 return $returnMw;
777 }
778
779 /**
780 * @param $code string: The code of the language for which to get the name
781 * @param $inLanguage null|string: Code of language in which to return the name (null for autonyms)
782 * @param $include string: 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
783 * @return string: Language name or empty
784 * @since 1.20
785 */
786 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
787 $array = self::fetchLanguageNames( $inLanguage, $include );
788 return !array_key_exists( $code, $array ) ? '' : $array[$code];
789 }
790
791 /**
792 * Get a message from the MediaWiki namespace.
793 *
794 * @param $msg String: message name
795 * @return string
796 */
797 function getMessageFromDB( $msg ) {
798 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
799 }
800
801 /**
802 * Get the native language name of $code.
803 * Only if defined in MediaWiki, no other data like CLDR.
804 * @param $code string
805 * @return string
806 * @deprecated in 1.20, use fetchLanguageName()
807 */
808 function getLanguageName( $code ) {
809 return self::fetchLanguageName( $code );
810 }
811
812 /**
813 * @param $key string
814 * @return string
815 */
816 function getMonthName( $key ) {
817 return $this->getMessageFromDB( self::$mMonthMsgs[$key - 1] );
818 }
819
820 /**
821 * @return array
822 */
823 function getMonthNamesArray() {
824 $monthNames = array( '' );
825 for ( $i = 1; $i < 13; $i++ ) {
826 $monthNames[] = $this->getMonthName( $i );
827 }
828 return $monthNames;
829 }
830
831 /**
832 * @param $key string
833 * @return string
834 */
835 function getMonthNameGen( $key ) {
836 return $this->getMessageFromDB( self::$mMonthGenMsgs[$key - 1] );
837 }
838
839 /**
840 * @param $key string
841 * @return string
842 */
843 function getMonthAbbreviation( $key ) {
844 return $this->getMessageFromDB( self::$mMonthAbbrevMsgs[$key - 1] );
845 }
846
847 /**
848 * @return array
849 */
850 function getMonthAbbreviationsArray() {
851 $monthNames = array( '' );
852 for ( $i = 1; $i < 13; $i++ ) {
853 $monthNames[] = $this->getMonthAbbreviation( $i );
854 }
855 return $monthNames;
856 }
857
858 /**
859 * @param $key string
860 * @return string
861 */
862 function getWeekdayName( $key ) {
863 return $this->getMessageFromDB( self::$mWeekdayMsgs[$key - 1] );
864 }
865
866 /**
867 * @param $key string
868 * @return string
869 */
870 function getWeekdayAbbreviation( $key ) {
871 return $this->getMessageFromDB( self::$mWeekdayAbbrevMsgs[$key - 1] );
872 }
873
874 /**
875 * @param $key string
876 * @return string
877 */
878 function getIranianCalendarMonthName( $key ) {
879 return $this->getMessageFromDB( self::$mIranianCalendarMonthMsgs[$key - 1] );
880 }
881
882 /**
883 * @param $key string
884 * @return string
885 */
886 function getHebrewCalendarMonthName( $key ) {
887 return $this->getMessageFromDB( self::$mHebrewCalendarMonthMsgs[$key - 1] );
888 }
889
890 /**
891 * @param $key string
892 * @return string
893 */
894 function getHebrewCalendarMonthNameGen( $key ) {
895 return $this->getMessageFromDB( self::$mHebrewCalendarMonthGenMsgs[$key - 1] );
896 }
897
898 /**
899 * @param $key string
900 * @return string
901 */
902 function getHijriCalendarMonthName( $key ) {
903 return $this->getMessageFromDB( self::$mHijriCalendarMonthMsgs[$key - 1] );
904 }
905
906 /**
907 * This is a workalike of PHP's date() function, but with better
908 * internationalisation, a reduced set of format characters, and a better
909 * escaping format.
910 *
911 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
912 * PHP manual for definitions. There are a number of extensions, which
913 * start with "x":
914 *
915 * xn Do not translate digits of the next numeric format character
916 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
917 * xr Use roman numerals for the next numeric format character
918 * xh Use hebrew numerals for the next numeric format character
919 * xx Literal x
920 * xg Genitive month name
921 *
922 * xij j (day number) in Iranian calendar
923 * xiF F (month name) in Iranian calendar
924 * xin n (month number) in Iranian calendar
925 * xiy y (two digit year) in Iranian calendar
926 * xiY Y (full year) in Iranian calendar
927 *
928 * xjj j (day number) in Hebrew calendar
929 * xjF F (month name) in Hebrew calendar
930 * xjt t (days in month) in Hebrew calendar
931 * xjx xg (genitive month name) in Hebrew calendar
932 * xjn n (month number) in Hebrew calendar
933 * xjY Y (full year) in Hebrew calendar
934 *
935 * xmj j (day number) in Hijri calendar
936 * xmF F (month name) in Hijri calendar
937 * xmn n (month number) in Hijri calendar
938 * xmY Y (full year) in Hijri calendar
939 *
940 * xkY Y (full year) in Thai solar calendar. Months and days are
941 * identical to the Gregorian calendar
942 * xoY Y (full year) in Minguo calendar or Juche year.
943 * Months and days are identical to the
944 * Gregorian calendar
945 * xtY Y (full year) in Japanese nengo. Months and days are
946 * identical to the Gregorian calendar
947 *
948 * Characters enclosed in double quotes will be considered literal (with
949 * the quotes themselves removed). Unmatched quotes will be considered
950 * literal quotes. Example:
951 *
952 * "The month is" F => The month is January
953 * i's" => 20'11"
954 *
955 * Backslash escaping is also supported.
956 *
957 * Input timestamp is assumed to be pre-normalized to the desired local
958 * time zone, if any.
959 *
960 * @param $format String
961 * @param $ts String: 14-character timestamp
962 * YYYYMMDDHHMMSS
963 * 01234567890123
964 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
965 *
966 * @return string
967 */
968 function sprintfDate( $format, $ts ) {
969 $s = '';
970 $raw = false;
971 $roman = false;
972 $hebrewNum = false;
973 $unix = false;
974 $rawToggle = false;
975 $iranian = false;
976 $hebrew = false;
977 $hijri = false;
978 $thai = false;
979 $minguo = false;
980 $tenno = false;
981 for ( $p = 0; $p < strlen( $format ); $p++ ) {
982 $num = false;
983 $code = $format[$p];
984 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
985 $code .= $format[++$p];
986 }
987
988 if ( ( $code === 'xi' || $code == 'xj' || $code == 'xk' || $code == 'xm' || $code == 'xo' || $code == 'xt' ) && $p < strlen( $format ) - 1 ) {
989 $code .= $format[++$p];
990 }
991
992 switch ( $code ) {
993 case 'xx':
994 $s .= 'x';
995 break;
996 case 'xn':
997 $raw = true;
998 break;
999 case 'xN':
1000 $rawToggle = !$rawToggle;
1001 break;
1002 case 'xr':
1003 $roman = true;
1004 break;
1005 case 'xh':
1006 $hebrewNum = true;
1007 break;
1008 case 'xg':
1009 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1010 break;
1011 case 'xjx':
1012 if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
1013 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1014 break;
1015 case 'd':
1016 $num = substr( $ts, 6, 2 );
1017 break;
1018 case 'D':
1019 if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
1020 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) + 1 );
1021 break;
1022 case 'j':
1023 $num = intval( substr( $ts, 6, 2 ) );
1024 break;
1025 case 'xij':
1026 if ( !$iranian ) {
1027 $iranian = self::tsToIranian( $ts );
1028 }
1029 $num = $iranian[2];
1030 break;
1031 case 'xmj':
1032 if ( !$hijri ) {
1033 $hijri = self::tsToHijri( $ts );
1034 }
1035 $num = $hijri[2];
1036 break;
1037 case 'xjj':
1038 if ( !$hebrew ) {
1039 $hebrew = self::tsToHebrew( $ts );
1040 }
1041 $num = $hebrew[2];
1042 break;
1043 case 'l':
1044 if ( !$unix ) {
1045 $unix = wfTimestamp( TS_UNIX, $ts );
1046 }
1047 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) + 1 );
1048 break;
1049 case 'N':
1050 if ( !$unix ) {
1051 $unix = wfTimestamp( TS_UNIX, $ts );
1052 }
1053 $w = gmdate( 'w', $unix );
1054 $num = $w ? $w : 7;
1055 break;
1056 case 'w':
1057 if ( !$unix ) {
1058 $unix = wfTimestamp( TS_UNIX, $ts );
1059 }
1060 $num = gmdate( 'w', $unix );
1061 break;
1062 case 'z':
1063 if ( !$unix ) {
1064 $unix = wfTimestamp( TS_UNIX, $ts );
1065 }
1066 $num = gmdate( 'z', $unix );
1067 break;
1068 case 'W':
1069 if ( !$unix ) {
1070 $unix = wfTimestamp( TS_UNIX, $ts );
1071 }
1072 $num = gmdate( 'W', $unix );
1073 break;
1074 case 'F':
1075 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1076 break;
1077 case 'xiF':
1078 if ( !$iranian ) {
1079 $iranian = self::tsToIranian( $ts );
1080 }
1081 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1082 break;
1083 case 'xmF':
1084 if ( !$hijri ) {
1085 $hijri = self::tsToHijri( $ts );
1086 }
1087 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1088 break;
1089 case 'xjF':
1090 if ( !$hebrew ) {
1091 $hebrew = self::tsToHebrew( $ts );
1092 }
1093 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1094 break;
1095 case 'm':
1096 $num = substr( $ts, 4, 2 );
1097 break;
1098 case 'M':
1099 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1100 break;
1101 case 'n':
1102 $num = intval( substr( $ts, 4, 2 ) );
1103 break;
1104 case 'xin':
1105 if ( !$iranian ) {
1106 $iranian = self::tsToIranian( $ts );
1107 }
1108 $num = $iranian[1];
1109 break;
1110 case 'xmn':
1111 if ( !$hijri ) {
1112 $hijri = self::tsToHijri ( $ts );
1113 }
1114 $num = $hijri[1];
1115 break;
1116 case 'xjn':
1117 if ( !$hebrew ) {
1118 $hebrew = self::tsToHebrew( $ts );
1119 }
1120 $num = $hebrew[1];
1121 break;
1122 case 't':
1123 if ( !$unix ) {
1124 $unix = wfTimestamp( TS_UNIX, $ts );
1125 }
1126 $num = gmdate( 't', $unix );
1127 break;
1128 case 'xjt':
1129 if ( !$hebrew ) {
1130 $hebrew = self::tsToHebrew( $ts );
1131 }
1132 $num = $hebrew[3];
1133 break;
1134 case 'L':
1135 if ( !$unix ) {
1136 $unix = wfTimestamp( TS_UNIX, $ts );
1137 }
1138 $num = gmdate( 'L', $unix );
1139 break;
1140 case 'o':
1141 if ( !$unix ) {
1142 $unix = wfTimestamp( TS_UNIX, $ts );
1143 }
1144 $num = gmdate( 'o', $unix );
1145 break;
1146 case 'Y':
1147 $num = substr( $ts, 0, 4 );
1148 break;
1149 case 'xiY':
1150 if ( !$iranian ) {
1151 $iranian = self::tsToIranian( $ts );
1152 }
1153 $num = $iranian[0];
1154 break;
1155 case 'xmY':
1156 if ( !$hijri ) {
1157 $hijri = self::tsToHijri( $ts );
1158 }
1159 $num = $hijri[0];
1160 break;
1161 case 'xjY':
1162 if ( !$hebrew ) {
1163 $hebrew = self::tsToHebrew( $ts );
1164 }
1165 $num = $hebrew[0];
1166 break;
1167 case 'xkY':
1168 if ( !$thai ) {
1169 $thai = self::tsToYear( $ts, 'thai' );
1170 }
1171 $num = $thai[0];
1172 break;
1173 case 'xoY':
1174 if ( !$minguo ) {
1175 $minguo = self::tsToYear( $ts, 'minguo' );
1176 }
1177 $num = $minguo[0];
1178 break;
1179 case 'xtY':
1180 if ( !$tenno ) {
1181 $tenno = self::tsToYear( $ts, 'tenno' );
1182 }
1183 $num = $tenno[0];
1184 break;
1185 case 'y':
1186 $num = substr( $ts, 2, 2 );
1187 break;
1188 case 'xiy':
1189 if ( !$iranian ) {
1190 $iranian = self::tsToIranian( $ts );
1191 }
1192 $num = substr( $iranian[0], -2 );
1193 break;
1194 case 'a':
1195 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
1196 break;
1197 case 'A':
1198 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
1199 break;
1200 case 'g':
1201 $h = substr( $ts, 8, 2 );
1202 $num = $h % 12 ? $h % 12 : 12;
1203 break;
1204 case 'G':
1205 $num = intval( substr( $ts, 8, 2 ) );
1206 break;
1207 case 'h':
1208 $h = substr( $ts, 8, 2 );
1209 $num = sprintf( '%02d', $h % 12 ? $h % 12 : 12 );
1210 break;
1211 case 'H':
1212 $num = substr( $ts, 8, 2 );
1213 break;
1214 case 'i':
1215 $num = substr( $ts, 10, 2 );
1216 break;
1217 case 's':
1218 $num = substr( $ts, 12, 2 );
1219 break;
1220 case 'c':
1221 if ( !$unix ) {
1222 $unix = wfTimestamp( TS_UNIX, $ts );
1223 }
1224 $s .= gmdate( 'c', $unix );
1225 break;
1226 case 'r':
1227 if ( !$unix ) {
1228 $unix = wfTimestamp( TS_UNIX, $ts );
1229 }
1230 $s .= gmdate( 'r', $unix );
1231 break;
1232 case 'U':
1233 if ( !$unix ) {
1234 $unix = wfTimestamp( TS_UNIX, $ts );
1235 }
1236 $num = $unix;
1237 break;
1238 case '\\':
1239 # Backslash escaping
1240 if ( $p < strlen( $format ) - 1 ) {
1241 $s .= $format[++$p];
1242 } else {
1243 $s .= '\\';
1244 }
1245 break;
1246 case '"':
1247 # Quoted literal
1248 if ( $p < strlen( $format ) - 1 ) {
1249 $endQuote = strpos( $format, '"', $p + 1 );
1250 if ( $endQuote === false ) {
1251 # No terminating quote, assume literal "
1252 $s .= '"';
1253 } else {
1254 $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
1255 $p = $endQuote;
1256 }
1257 } else {
1258 # Quote at end of string, assume literal "
1259 $s .= '"';
1260 }
1261 break;
1262 default:
1263 $s .= $format[$p];
1264 }
1265 if ( $num !== false ) {
1266 if ( $rawToggle || $raw ) {
1267 $s .= $num;
1268 $raw = false;
1269 } elseif ( $roman ) {
1270 $s .= self::romanNumeral( $num );
1271 $roman = false;
1272 } elseif ( $hebrewNum ) {
1273 $s .= self::hebrewNumeral( $num );
1274 $hebrewNum = false;
1275 } else {
1276 $s .= $this->formatNum( $num, true );
1277 }
1278 }
1279 }
1280 return $s;
1281 }
1282
1283 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1284 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1285
1286 /**
1287 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1288 * Gregorian dates to Iranian dates. Originally written in C, it
1289 * is released under the terms of GNU Lesser General Public
1290 * License. Conversion to PHP was performed by Niklas Laxström.
1291 *
1292 * Link: http://www.farsiweb.info/jalali/jalali.c
1293 *
1294 * @param $ts string
1295 *
1296 * @return string
1297 */
1298 private static function tsToIranian( $ts ) {
1299 $gy = substr( $ts, 0, 4 ) -1600;
1300 $gm = substr( $ts, 4, 2 ) -1;
1301 $gd = substr( $ts, 6, 2 ) -1;
1302
1303 # Days passed from the beginning (including leap years)
1304 $gDayNo = 365 * $gy
1305 + floor( ( $gy + 3 ) / 4 )
1306 - floor( ( $gy + 99 ) / 100 )
1307 + floor( ( $gy + 399 ) / 400 );
1308
1309 // Add days of the past months of this year
1310 for ( $i = 0; $i < $gm; $i++ ) {
1311 $gDayNo += self::$GREG_DAYS[$i];
1312 }
1313
1314 // Leap years
1315 if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) {
1316 $gDayNo++;
1317 }
1318
1319 // Days passed in current month
1320 $gDayNo += (int)$gd;
1321
1322 $jDayNo = $gDayNo - 79;
1323
1324 $jNp = floor( $jDayNo / 12053 );
1325 $jDayNo %= 12053;
1326
1327 $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
1328 $jDayNo %= 1461;
1329
1330 if ( $jDayNo >= 366 ) {
1331 $jy += floor( ( $jDayNo - 1 ) / 365 );
1332 $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
1333 }
1334
1335 for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
1336 $jDayNo -= self::$IRANIAN_DAYS[$i];
1337 }
1338
1339 $jm = $i + 1;
1340 $jd = $jDayNo + 1;
1341
1342 return array( $jy, $jm, $jd );
1343 }
1344
1345 /**
1346 * Converting Gregorian dates to Hijri dates.
1347 *
1348 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1349 *
1350 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1351 *
1352 * @param $ts string
1353 *
1354 * @return string
1355 */
1356 private static function tsToHijri( $ts ) {
1357 $year = substr( $ts, 0, 4 );
1358 $month = substr( $ts, 4, 2 );
1359 $day = substr( $ts, 6, 2 );
1360
1361 $zyr = $year;
1362 $zd = $day;
1363 $zm = $month;
1364 $zy = $zyr;
1365
1366 if (
1367 ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1368 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1369 )
1370 {
1371 $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1372 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1373 (int)( ( 3 * (int)( ( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1374 $zd - 32075;
1375 } else {
1376 $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1377 (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
1378 }
1379
1380 $zl = $zjd -1948440 + 10632;
1381 $zn = (int)( ( $zl - 1 ) / 10631 );
1382 $zl = $zl - 10631 * $zn + 354;
1383 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) + ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1384 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
1385 $zm = (int)( ( 24 * $zl ) / 709 );
1386 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1387 $zy = 30 * $zn + $zj - 30;
1388
1389 return array( $zy, $zm, $zd );
1390 }
1391
1392 /**
1393 * Converting Gregorian dates to Hebrew dates.
1394 *
1395 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1396 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1397 * to translate the relevant functions into PHP and release them under
1398 * GNU GPL.
1399 *
1400 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1401 * and Adar II is 14. In a non-leap year, Adar is 6.
1402 *
1403 * @param $ts string
1404 *
1405 * @return string
1406 */
1407 private static function tsToHebrew( $ts ) {
1408 # Parse date
1409 $year = substr( $ts, 0, 4 );
1410 $month = substr( $ts, 4, 2 );
1411 $day = substr( $ts, 6, 2 );
1412
1413 # Calculate Hebrew year
1414 $hebrewYear = $year + 3760;
1415
1416 # Month number when September = 1, August = 12
1417 $month += 4;
1418 if ( $month > 12 ) {
1419 # Next year
1420 $month -= 12;
1421 $year++;
1422 $hebrewYear++;
1423 }
1424
1425 # Calculate day of year from 1 September
1426 $dayOfYear = $day;
1427 for ( $i = 1; $i < $month; $i++ ) {
1428 if ( $i == 6 ) {
1429 # February
1430 $dayOfYear += 28;
1431 # Check if the year is leap
1432 if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
1433 $dayOfYear++;
1434 }
1435 } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
1436 $dayOfYear += 30;
1437 } else {
1438 $dayOfYear += 31;
1439 }
1440 }
1441
1442 # Calculate the start of the Hebrew year
1443 $start = self::hebrewYearStart( $hebrewYear );
1444
1445 # Calculate next year's start
1446 if ( $dayOfYear <= $start ) {
1447 # Day is before the start of the year - it is the previous year
1448 # Next year's start
1449 $nextStart = $start;
1450 # Previous year
1451 $year--;
1452 $hebrewYear--;
1453 # Add days since previous year's 1 September
1454 $dayOfYear += 365;
1455 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1456 # Leap year
1457 $dayOfYear++;
1458 }
1459 # Start of the new (previous) year
1460 $start = self::hebrewYearStart( $hebrewYear );
1461 } else {
1462 # Next year's start
1463 $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
1464 }
1465
1466 # Calculate Hebrew day of year
1467 $hebrewDayOfYear = $dayOfYear - $start;
1468
1469 # Difference between year's days
1470 $diff = $nextStart - $start;
1471 # Add 12 (or 13 for leap years) days to ignore the difference between
1472 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1473 # difference is only about the year type
1474 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1475 $diff += 13;
1476 } else {
1477 $diff += 12;
1478 }
1479
1480 # Check the year pattern, and is leap year
1481 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1482 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1483 # and non-leap years
1484 $yearPattern = $diff % 30;
1485 # Check if leap year
1486 $isLeap = $diff >= 30;
1487
1488 # Calculate day in the month from number of day in the Hebrew year
1489 # Don't check Adar - if the day is not in Adar, we will stop before;
1490 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1491 $hebrewDay = $hebrewDayOfYear;
1492 $hebrewMonth = 1;
1493 $days = 0;
1494 while ( $hebrewMonth <= 12 ) {
1495 # Calculate days in this month
1496 if ( $isLeap && $hebrewMonth == 6 ) {
1497 # Adar in a leap year
1498 if ( $isLeap ) {
1499 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1500 $days = 30;
1501 if ( $hebrewDay <= $days ) {
1502 # Day in Adar I
1503 $hebrewMonth = 13;
1504 } else {
1505 # Subtract the days of Adar I
1506 $hebrewDay -= $days;
1507 # Try Adar II
1508 $days = 29;
1509 if ( $hebrewDay <= $days ) {
1510 # Day in Adar II
1511 $hebrewMonth = 14;
1512 }
1513 }
1514 }
1515 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1516 # Cheshvan in a complete year (otherwise as the rule below)
1517 $days = 30;
1518 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1519 # Kislev in an incomplete year (otherwise as the rule below)
1520 $days = 29;
1521 } else {
1522 # Odd months have 30 days, even have 29
1523 $days = 30 - ( $hebrewMonth - 1 ) % 2;
1524 }
1525 if ( $hebrewDay <= $days ) {
1526 # In the current month
1527 break;
1528 } else {
1529 # Subtract the days of the current month
1530 $hebrewDay -= $days;
1531 # Try in the next month
1532 $hebrewMonth++;
1533 }
1534 }
1535
1536 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1537 }
1538
1539 /**
1540 * This calculates the Hebrew year start, as days since 1 September.
1541 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1542 * Used for Hebrew date.
1543 *
1544 * @param $year int
1545 *
1546 * @return string
1547 */
1548 private static function hebrewYearStart( $year ) {
1549 $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
1550 $b = intval( ( $year - 1 ) % 4 );
1551 $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1552 if ( $m < 0 ) {
1553 $m--;
1554 }
1555 $Mar = intval( $m );
1556 if ( $m < 0 ) {
1557 $m++;
1558 }
1559 $m -= $Mar;
1560
1561 $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7 );
1562 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1563 $Mar++;
1564 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1565 $Mar += 2;
1566 } elseif ( $c == 2 || $c == 4 || $c == 6 ) {
1567 $Mar++;
1568 }
1569
1570 $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1571 return $Mar;
1572 }
1573
1574 /**
1575 * Algorithm to convert Gregorian dates to Thai solar dates,
1576 * Minguo dates or Minguo dates.
1577 *
1578 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1579 * http://en.wikipedia.org/wiki/Minguo_calendar
1580 * http://en.wikipedia.org/wiki/Japanese_era_name
1581 *
1582 * @param $ts String: 14-character timestamp
1583 * @param $cName String: calender name
1584 * @return Array: converted year, month, day
1585 */
1586 private static function tsToYear( $ts, $cName ) {
1587 $gy = substr( $ts, 0, 4 );
1588 $gm = substr( $ts, 4, 2 );
1589 $gd = substr( $ts, 6, 2 );
1590
1591 if ( !strcmp( $cName, 'thai' ) ) {
1592 # Thai solar dates
1593 # Add 543 years to the Gregorian calendar
1594 # Months and days are identical
1595 $gy_offset = $gy + 543;
1596 } elseif ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
1597 # Minguo dates
1598 # Deduct 1911 years from the Gregorian calendar
1599 # Months and days are identical
1600 $gy_offset = $gy - 1911;
1601 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1602 # Nengō dates up to Meiji period
1603 # Deduct years from the Gregorian calendar
1604 # depending on the nengo periods
1605 # Months and days are identical
1606 if ( ( $gy < 1912 ) || ( ( $gy == 1912 ) && ( $gm < 7 ) ) || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1607 # Meiji period
1608 $gy_gannen = $gy - 1868 + 1;
1609 $gy_offset = $gy_gannen;
1610 if ( $gy_gannen == 1 ) {
1611 $gy_offset = '元';
1612 }
1613 $gy_offset = '明治' . $gy_offset;
1614 } elseif (
1615 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1616 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1617 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1618 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1619 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1620 )
1621 {
1622 # Taishō period
1623 $gy_gannen = $gy - 1912 + 1;
1624 $gy_offset = $gy_gannen;
1625 if ( $gy_gannen == 1 ) {
1626 $gy_offset = '元';
1627 }
1628 $gy_offset = '大正' . $gy_offset;
1629 } elseif (
1630 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1631 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1632 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1633 )
1634 {
1635 # Shōwa period
1636 $gy_gannen = $gy - 1926 + 1;
1637 $gy_offset = $gy_gannen;
1638 if ( $gy_gannen == 1 ) {
1639 $gy_offset = '元';
1640 }
1641 $gy_offset = '昭和' . $gy_offset;
1642 } else {
1643 # Heisei period
1644 $gy_gannen = $gy - 1989 + 1;
1645 $gy_offset = $gy_gannen;
1646 if ( $gy_gannen == 1 ) {
1647 $gy_offset = '元';
1648 }
1649 $gy_offset = '平成' . $gy_offset;
1650 }
1651 } else {
1652 $gy_offset = $gy;
1653 }
1654
1655 return array( $gy_offset, $gm, $gd );
1656 }
1657
1658 /**
1659 * Roman number formatting up to 3000
1660 *
1661 * @param $num int
1662 *
1663 * @return string
1664 */
1665 static function romanNumeral( $num ) {
1666 static $table = array(
1667 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1668 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1669 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1670 array( '', 'M', 'MM', 'MMM' )
1671 );
1672
1673 $num = intval( $num );
1674 if ( $num > 3000 || $num <= 0 ) {
1675 return $num;
1676 }
1677
1678 $s = '';
1679 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1680 if ( $num >= $pow10 ) {
1681 $s .= $table[$i][(int)floor( $num / $pow10 )];
1682 }
1683 $num = $num % $pow10;
1684 }
1685 return $s;
1686 }
1687
1688 /**
1689 * Hebrew Gematria number formatting up to 9999
1690 *
1691 * @param $num int
1692 *
1693 * @return string
1694 */
1695 static function hebrewNumeral( $num ) {
1696 static $table = array(
1697 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1698 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1699 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1700 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1701 );
1702
1703 $num = intval( $num );
1704 if ( $num > 9999 || $num <= 0 ) {
1705 return $num;
1706 }
1707
1708 $s = '';
1709 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1710 if ( $num >= $pow10 ) {
1711 if ( $num == 15 || $num == 16 ) {
1712 $s .= $table[0][9] . $table[0][$num - 9];
1713 $num = 0;
1714 } else {
1715 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1716 if ( $pow10 == 1000 ) {
1717 $s .= "'";
1718 }
1719 }
1720 }
1721 $num = $num % $pow10;
1722 }
1723 if ( strlen( $s ) == 2 ) {
1724 $str = $s . "'";
1725 } else {
1726 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1727 $str .= substr( $s, strlen( $s ) - 2, 2 );
1728 }
1729 $start = substr( $str, 0, strlen( $str ) - 2 );
1730 $end = substr( $str, strlen( $str ) - 2 );
1731 switch( $end ) {
1732 case 'כ':
1733 $str = $start . 'ך';
1734 break;
1735 case 'מ':
1736 $str = $start . 'ם';
1737 break;
1738 case 'נ':
1739 $str = $start . 'ן';
1740 break;
1741 case 'פ':
1742 $str = $start . 'ף';
1743 break;
1744 case 'צ':
1745 $str = $start . 'ץ';
1746 break;
1747 }
1748 return $str;
1749 }
1750
1751 /**
1752 * Used by date() and time() to adjust the time output.
1753 *
1754 * @param $ts Int the time in date('YmdHis') format
1755 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1756 * get user timecorrection setting)
1757 * @return int
1758 */
1759 function userAdjust( $ts, $tz = false ) {
1760 global $wgUser, $wgLocalTZoffset;
1761
1762 if ( $tz === false ) {
1763 $tz = $wgUser->getOption( 'timecorrection' );
1764 }
1765
1766 $data = explode( '|', $tz, 3 );
1767
1768 if ( $data[0] == 'ZoneInfo' ) {
1769 wfSuppressWarnings();
1770 $userTZ = timezone_open( $data[2] );
1771 wfRestoreWarnings();
1772 if ( $userTZ !== false ) {
1773 $date = date_create( $ts, timezone_open( 'UTC' ) );
1774 date_timezone_set( $date, $userTZ );
1775 $date = date_format( $date, 'YmdHis' );
1776 return $date;
1777 }
1778 # Unrecognized timezone, default to 'Offset' with the stored offset.
1779 $data[0] = 'Offset';
1780 }
1781
1782 $minDiff = 0;
1783 if ( $data[0] == 'System' || $tz == '' ) {
1784 #  Global offset in minutes.
1785 if ( isset( $wgLocalTZoffset ) ) {
1786 $minDiff = $wgLocalTZoffset;
1787 }
1788 } elseif ( $data[0] == 'Offset' ) {
1789 $minDiff = intval( $data[1] );
1790 } else {
1791 $data = explode( ':', $tz );
1792 if ( count( $data ) == 2 ) {
1793 $data[0] = intval( $data[0] );
1794 $data[1] = intval( $data[1] );
1795 $minDiff = abs( $data[0] ) * 60 + $data[1];
1796 if ( $data[0] < 0 ) {
1797 $minDiff = -$minDiff;
1798 }
1799 } else {
1800 $minDiff = intval( $data[0] ) * 60;
1801 }
1802 }
1803
1804 # No difference ? Return time unchanged
1805 if ( 0 == $minDiff ) {
1806 return $ts;
1807 }
1808
1809 wfSuppressWarnings(); // E_STRICT system time bitching
1810 # Generate an adjusted date; take advantage of the fact that mktime
1811 # will normalize out-of-range values so we don't have to split $minDiff
1812 # into hours and minutes.
1813 $t = mktime( (
1814 (int)substr( $ts, 8, 2 ) ), # Hours
1815 (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
1816 (int)substr( $ts, 12, 2 ), # Seconds
1817 (int)substr( $ts, 4, 2 ), # Month
1818 (int)substr( $ts, 6, 2 ), # Day
1819 (int)substr( $ts, 0, 4 ) ); # Year
1820
1821 $date = date( 'YmdHis', $t );
1822 wfRestoreWarnings();
1823
1824 return $date;
1825 }
1826
1827 /**
1828 * This is meant to be used by time(), date(), and timeanddate() to get
1829 * the date preference they're supposed to use, it should be used in
1830 * all children.
1831 *
1832 *<code>
1833 * function timeanddate([...], $format = true) {
1834 * $datePreference = $this->dateFormat($format);
1835 * [...]
1836 * }
1837 *</code>
1838 *
1839 * @param $usePrefs Mixed: if true, the user's preference is used
1840 * if false, the site/language default is used
1841 * if int/string, assumed to be a format.
1842 * @return string
1843 */
1844 function dateFormat( $usePrefs = true ) {
1845 global $wgUser;
1846
1847 if ( is_bool( $usePrefs ) ) {
1848 if ( $usePrefs ) {
1849 $datePreference = $wgUser->getDatePreference();
1850 } else {
1851 $datePreference = (string)User::getDefaultOption( 'date' );
1852 }
1853 } else {
1854 $datePreference = (string)$usePrefs;
1855 }
1856
1857 // return int
1858 if ( $datePreference == '' ) {
1859 return 'default';
1860 }
1861
1862 return $datePreference;
1863 }
1864
1865 /**
1866 * Get a format string for a given type and preference
1867 * @param $type string May be date, time or both
1868 * @param $pref string The format name as it appears in Messages*.php
1869 *
1870 * @return string
1871 */
1872 function getDateFormatString( $type, $pref ) {
1873 if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
1874 if ( $pref == 'default' ) {
1875 $pref = $this->getDefaultDateFormat();
1876 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1877 } else {
1878 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1879 if ( is_null( $df ) ) {
1880 $pref = $this->getDefaultDateFormat();
1881 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1882 }
1883 }
1884 $this->dateFormatStrings[$type][$pref] = $df;
1885 }
1886 return $this->dateFormatStrings[$type][$pref];
1887 }
1888
1889 /**
1890 * @param $ts Mixed: the time format which needs to be turned into a
1891 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1892 * @param $adj Bool: whether to adjust the time output according to the
1893 * user configured offset ($timecorrection)
1894 * @param $format Mixed: true to use user's date format preference
1895 * @param $timecorrection String|bool the time offset as returned by
1896 * validateTimeZone() in Special:Preferences
1897 * @return string
1898 */
1899 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1900 $ts = wfTimestamp( TS_MW, $ts );
1901 if ( $adj ) {
1902 $ts = $this->userAdjust( $ts, $timecorrection );
1903 }
1904 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1905 return $this->sprintfDate( $df, $ts );
1906 }
1907
1908 /**
1909 * @param $ts Mixed: the time format which needs to be turned into a
1910 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1911 * @param $adj Bool: whether to adjust the time output according to the
1912 * user configured offset ($timecorrection)
1913 * @param $format Mixed: true to use user's date format preference
1914 * @param $timecorrection String|bool the time offset as returned by
1915 * validateTimeZone() in Special:Preferences
1916 * @return string
1917 */
1918 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1919 $ts = wfTimestamp( TS_MW, $ts );
1920 if ( $adj ) {
1921 $ts = $this->userAdjust( $ts, $timecorrection );
1922 }
1923 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1924 return $this->sprintfDate( $df, $ts );
1925 }
1926
1927 /**
1928 * @param $ts Mixed: the time format which needs to be turned into a
1929 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1930 * @param $adj Bool: whether to adjust the time output according to the
1931 * user configured offset ($timecorrection)
1932 * @param $format Mixed: what format to return, if it's false output the
1933 * default one (default true)
1934 * @param $timecorrection String|bool the time offset as returned by
1935 * validateTimeZone() in Special:Preferences
1936 * @return string
1937 */
1938 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1939 $ts = wfTimestamp( TS_MW, $ts );
1940 if ( $adj ) {
1941 $ts = $this->userAdjust( $ts, $timecorrection );
1942 }
1943 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1944 return $this->sprintfDate( $df, $ts );
1945 }
1946
1947 /**
1948 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
1949 *
1950 * @since 1.20
1951 *
1952 * @param integer $seconds The amount of seconds.
1953 * @param array $chosenIntervals The intervals to enable.
1954 *
1955 * @return string
1956 */
1957 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
1958 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
1959
1960 $segments = array();
1961
1962 foreach ( $intervals as $intervalName => $intervalValue ) {
1963 $message = new Message( 'duration-' . $intervalName, array( $intervalValue ) );
1964 $segments[] = $message->inLanguage( $this )->escaped();
1965 }
1966
1967 return $this->listToText( $segments );
1968 }
1969
1970 /**
1971 * Takes a number of seconds and returns an array with a set of corresponding intervals.
1972 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
1973 *
1974 * @since 1.20
1975 *
1976 * @param integer $seconds The amount of seconds.
1977 * @param array $chosenIntervals The intervals to enable.
1978 *
1979 * @return array
1980 */
1981 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
1982 if ( empty( $chosenIntervals ) ) {
1983 $chosenIntervals = array( 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', 'seconds' );
1984 }
1985
1986 $intervals = array_intersect_key( self::$durationIntervals, array_flip( $chosenIntervals ) );
1987 $sortedNames = array_keys( $intervals );
1988 $smallestInterval = array_pop( $sortedNames );
1989
1990 $segments = array();
1991
1992 foreach ( $intervals as $name => $length ) {
1993 $value = floor( $seconds / $length );
1994
1995 if ( $value > 0 || ( $name == $smallestInterval && empty( $segments ) ) ) {
1996 $seconds -= $value * $length;
1997 $segments[$name] = $value;
1998 }
1999 }
2000
2001 return $segments;
2002 }
2003
2004 /**
2005 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2006 *
2007 * @param $type String: can be 'date', 'time' or 'both'
2008 * @param $ts Mixed: the time format which needs to be turned into a
2009 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2010 * @param $user User object used to get preferences for timezone and format
2011 * @param $options Array, can contain the following keys:
2012 * - 'timecorrection': time correction, can have the following values:
2013 * - true: use user's preference
2014 * - false: don't use time correction
2015 * - integer: value of time correction in minutes
2016 * - 'format': format to use, can have the following values:
2017 * - true: use user's preference
2018 * - false: use default preference
2019 * - string: format to use
2020 * @since 1.19
2021 * @return String
2022 */
2023 private function internalUserTimeAndDate( $type, $ts, User $user, array $options ) {
2024 $ts = wfTimestamp( TS_MW, $ts );
2025 $options += array( 'timecorrection' => true, 'format' => true );
2026 if ( $options['timecorrection'] !== false ) {
2027 if ( $options['timecorrection'] === true ) {
2028 $offset = $user->getOption( 'timecorrection' );
2029 } else {
2030 $offset = $options['timecorrection'];
2031 }
2032 $ts = $this->userAdjust( $ts, $offset );
2033 }
2034 if ( $options['format'] === true ) {
2035 $format = $user->getDatePreference();
2036 } else {
2037 $format = $options['format'];
2038 }
2039 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2040 return $this->sprintfDate( $df, $ts );
2041 }
2042
2043 /**
2044 * Get the formatted date for the given timestamp and formatted for
2045 * the given user.
2046 *
2047 * @param $ts Mixed: the time format which needs to be turned into a
2048 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2049 * @param $user User object used to get preferences for timezone and format
2050 * @param $options Array, can contain the following keys:
2051 * - 'timecorrection': time correction, can have the following values:
2052 * - true: use user's preference
2053 * - false: don't use time correction
2054 * - integer: value of time correction in minutes
2055 * - 'format': format to use, can have the following values:
2056 * - true: use user's preference
2057 * - false: use default preference
2058 * - string: format to use
2059 * @since 1.19
2060 * @return String
2061 */
2062 public function userDate( $ts, User $user, array $options = array() ) {
2063 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2064 }
2065
2066 /**
2067 * Get the formatted time for the given timestamp and formatted for
2068 * the given user.
2069 *
2070 * @param $ts Mixed: the time format which needs to be turned into a
2071 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2072 * @param $user User object used to get preferences for timezone and format
2073 * @param $options Array, can contain the following keys:
2074 * - 'timecorrection': time correction, can have the following values:
2075 * - true: use user's preference
2076 * - false: don't use time correction
2077 * - integer: value of time correction in minutes
2078 * - 'format': format to use, can have the following values:
2079 * - true: use user's preference
2080 * - false: use default preference
2081 * - string: format to use
2082 * @since 1.19
2083 * @return String
2084 */
2085 public function userTime( $ts, User $user, array $options = array() ) {
2086 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2087 }
2088
2089 /**
2090 * Get the formatted date and time for the given timestamp and formatted for
2091 * the given user.
2092 *
2093 * @param $ts Mixed: the time format which needs to be turned into a
2094 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2095 * @param $user User object used to get preferences for timezone and format
2096 * @param $options Array, can contain the following keys:
2097 * - 'timecorrection': time correction, can have the following values:
2098 * - true: use user's preference
2099 * - false: don't use time correction
2100 * - integer: value of time correction in minutes
2101 * - 'format': format to use, can have the following values:
2102 * - true: use user's preference
2103 * - false: use default preference
2104 * - string: format to use
2105 * @since 1.19
2106 * @return String
2107 */
2108 public function userTimeAndDate( $ts, User $user, array $options = array() ) {
2109 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2110 }
2111
2112 /**
2113 * @param $key string
2114 * @return array|null
2115 */
2116 function getMessage( $key ) {
2117 return self::$dataCache->getSubitem( $this->mCode, 'messages', $key );
2118 }
2119
2120 /**
2121 * @return array
2122 */
2123 function getAllMessages() {
2124 return self::$dataCache->getItem( $this->mCode, 'messages' );
2125 }
2126
2127 /**
2128 * @param $in
2129 * @param $out
2130 * @param $string
2131 * @return string
2132 */
2133 function iconv( $in, $out, $string ) {
2134 # This is a wrapper for iconv in all languages except esperanto,
2135 # which does some nasty x-conversions beforehand
2136
2137 # Even with //IGNORE iconv can whine about illegal characters in
2138 # *input* string. We just ignore those too.
2139 # REF: http://bugs.php.net/bug.php?id=37166
2140 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2141 wfSuppressWarnings();
2142 $text = iconv( $in, $out . '//IGNORE', $string );
2143 wfRestoreWarnings();
2144 return $text;
2145 }
2146
2147 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2148
2149 /**
2150 * @param $matches array
2151 * @return mixed|string
2152 */
2153 function ucwordbreaksCallbackAscii( $matches ) {
2154 return $this->ucfirst( $matches[1] );
2155 }
2156
2157 /**
2158 * @param $matches array
2159 * @return string
2160 */
2161 function ucwordbreaksCallbackMB( $matches ) {
2162 return mb_strtoupper( $matches[0] );
2163 }
2164
2165 /**
2166 * @param $matches array
2167 * @return string
2168 */
2169 function ucCallback( $matches ) {
2170 list( $wikiUpperChars ) = self::getCaseMaps();
2171 return strtr( $matches[1], $wikiUpperChars );
2172 }
2173
2174 /**
2175 * @param $matches array
2176 * @return string
2177 */
2178 function lcCallback( $matches ) {
2179 list( , $wikiLowerChars ) = self::getCaseMaps();
2180 return strtr( $matches[1], $wikiLowerChars );
2181 }
2182
2183 /**
2184 * @param $matches array
2185 * @return string
2186 */
2187 function ucwordsCallbackMB( $matches ) {
2188 return mb_strtoupper( $matches[0] );
2189 }
2190
2191 /**
2192 * @param $matches array
2193 * @return string
2194 */
2195 function ucwordsCallbackWiki( $matches ) {
2196 list( $wikiUpperChars ) = self::getCaseMaps();
2197 return strtr( $matches[0], $wikiUpperChars );
2198 }
2199
2200 /**
2201 * Make a string's first character uppercase
2202 *
2203 * @param $str string
2204 *
2205 * @return string
2206 */
2207 function ucfirst( $str ) {
2208 $o = ord( $str );
2209 if ( $o < 96 ) { // if already uppercase...
2210 return $str;
2211 } elseif ( $o < 128 ) {
2212 return ucfirst( $str ); // use PHP's ucfirst()
2213 } else {
2214 // fall back to more complex logic in case of multibyte strings
2215 return $this->uc( $str, true );
2216 }
2217 }
2218
2219 /**
2220 * Convert a string to uppercase
2221 *
2222 * @param $str string
2223 * @param $first bool
2224 *
2225 * @return string
2226 */
2227 function uc( $str, $first = false ) {
2228 if ( function_exists( 'mb_strtoupper' ) ) {
2229 if ( $first ) {
2230 if ( $this->isMultibyte( $str ) ) {
2231 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2232 } else {
2233 return ucfirst( $str );
2234 }
2235 } else {
2236 return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
2237 }
2238 } else {
2239 if ( $this->isMultibyte( $str ) ) {
2240 $x = $first ? '^' : '';
2241 return preg_replace_callback(
2242 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2243 array( $this, 'ucCallback' ),
2244 $str
2245 );
2246 } else {
2247 return $first ? ucfirst( $str ) : strtoupper( $str );
2248 }
2249 }
2250 }
2251
2252 /**
2253 * @param $str string
2254 * @return mixed|string
2255 */
2256 function lcfirst( $str ) {
2257 $o = ord( $str );
2258 if ( !$o ) {
2259 return strval( $str );
2260 } elseif ( $o >= 128 ) {
2261 return $this->lc( $str, true );
2262 } elseif ( $o > 96 ) {
2263 return $str;
2264 } else {
2265 $str[0] = strtolower( $str[0] );
2266 return $str;
2267 }
2268 }
2269
2270 /**
2271 * @param $str string
2272 * @param $first bool
2273 * @return mixed|string
2274 */
2275 function lc( $str, $first = false ) {
2276 if ( function_exists( 'mb_strtolower' ) ) {
2277 if ( $first ) {
2278 if ( $this->isMultibyte( $str ) ) {
2279 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2280 } else {
2281 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2282 }
2283 } else {
2284 return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
2285 }
2286 } else {
2287 if ( $this->isMultibyte( $str ) ) {
2288 $x = $first ? '^' : '';
2289 return preg_replace_callback(
2290 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2291 array( $this, 'lcCallback' ),
2292 $str
2293 );
2294 } else {
2295 return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2296 }
2297 }
2298 }
2299
2300 /**
2301 * @param $str string
2302 * @return bool
2303 */
2304 function isMultibyte( $str ) {
2305 return (bool)preg_match( '/[\x80-\xff]/', $str );
2306 }
2307
2308 /**
2309 * @param $str string
2310 * @return mixed|string
2311 */
2312 function ucwords( $str ) {
2313 if ( $this->isMultibyte( $str ) ) {
2314 $str = $this->lc( $str );
2315
2316 // regexp to find first letter in each word (i.e. after each space)
2317 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2318
2319 // function to use to capitalize a single char
2320 if ( function_exists( 'mb_strtoupper' ) ) {
2321 return preg_replace_callback(
2322 $replaceRegexp,
2323 array( $this, 'ucwordsCallbackMB' ),
2324 $str
2325 );
2326 } else {
2327 return preg_replace_callback(
2328 $replaceRegexp,
2329 array( $this, 'ucwordsCallbackWiki' ),
2330 $str
2331 );
2332 }
2333 } else {
2334 return ucwords( strtolower( $str ) );
2335 }
2336 }
2337
2338 /**
2339 * capitalize words at word breaks
2340 *
2341 * @param $str string
2342 * @return mixed
2343 */
2344 function ucwordbreaks( $str ) {
2345 if ( $this->isMultibyte( $str ) ) {
2346 $str = $this->lc( $str );
2347
2348 // since \b doesn't work for UTF-8, we explicitely define word break chars
2349 $breaks = "[ \-\(\)\}\{\.,\?!]";
2350
2351 // find first letter after word break
2352 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2353
2354 if ( function_exists( 'mb_strtoupper' ) ) {
2355 return preg_replace_callback(
2356 $replaceRegexp,
2357 array( $this, 'ucwordbreaksCallbackMB' ),
2358 $str
2359 );
2360 } else {
2361 return preg_replace_callback(
2362 $replaceRegexp,
2363 array( $this, 'ucwordsCallbackWiki' ),
2364 $str
2365 );
2366 }
2367 } else {
2368 return preg_replace_callback(
2369 '/\b([\w\x80-\xff]+)\b/',
2370 array( $this, 'ucwordbreaksCallbackAscii' ),
2371 $str
2372 );
2373 }
2374 }
2375
2376 /**
2377 * Return a case-folded representation of $s
2378 *
2379 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2380 * and $s2 are the same except for the case of their characters. It is not
2381 * necessary for the value returned to make sense when displayed.
2382 *
2383 * Do *not* perform any other normalisation in this function. If a caller
2384 * uses this function when it should be using a more general normalisation
2385 * function, then fix the caller.
2386 *
2387 * @param $s string
2388 *
2389 * @return string
2390 */
2391 function caseFold( $s ) {
2392 return $this->uc( $s );
2393 }
2394
2395 /**
2396 * @param $s string
2397 * @return string
2398 */
2399 function checkTitleEncoding( $s ) {
2400 if ( is_array( $s ) ) {
2401 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2402 }
2403 # Check for non-UTF-8 URLs
2404 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2405 if ( !$ishigh ) {
2406 return $s;
2407 }
2408
2409 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2410 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2411 if ( $isutf8 ) {
2412 return $s;
2413 }
2414
2415 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2416 }
2417
2418 /**
2419 * @return array
2420 */
2421 function fallback8bitEncoding() {
2422 return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' );
2423 }
2424
2425 /**
2426 * Most writing systems use whitespace to break up words.
2427 * Some languages such as Chinese don't conventionally do this,
2428 * which requires special handling when breaking up words for
2429 * searching etc.
2430 *
2431 * @return bool
2432 */
2433 function hasWordBreaks() {
2434 return true;
2435 }
2436
2437 /**
2438 * Some languages such as Chinese require word segmentation,
2439 * Specify such segmentation when overridden in derived class.
2440 *
2441 * @param $string String
2442 * @return String
2443 */
2444 function segmentByWord( $string ) {
2445 return $string;
2446 }
2447
2448 /**
2449 * Some languages have special punctuation need to be normalized.
2450 * Make such changes here.
2451 *
2452 * @param $string String
2453 * @return String
2454 */
2455 function normalizeForSearch( $string ) {
2456 return self::convertDoubleWidth( $string );
2457 }
2458
2459 /**
2460 * convert double-width roman characters to single-width.
2461 * range: ff00-ff5f ~= 0020-007f
2462 *
2463 * @param $string string
2464 *
2465 * @return string
2466 */
2467 protected static function convertDoubleWidth( $string ) {
2468 static $full = null;
2469 static $half = null;
2470
2471 if ( $full === null ) {
2472 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2473 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2474 $full = str_split( $fullWidth, 3 );
2475 $half = str_split( $halfWidth );
2476 }
2477
2478 $string = str_replace( $full, $half, $string );
2479 return $string;
2480 }
2481
2482 /**
2483 * @param $string string
2484 * @param $pattern string
2485 * @return string
2486 */
2487 protected static function insertSpace( $string, $pattern ) {
2488 $string = preg_replace( $pattern, " $1 ", $string );
2489 $string = preg_replace( '/ +/', ' ', $string );
2490 return $string;
2491 }
2492
2493 /**
2494 * @param $termsArray array
2495 * @return array
2496 */
2497 function convertForSearchResult( $termsArray ) {
2498 # some languages, e.g. Chinese, need to do a conversion
2499 # in order for search results to be displayed correctly
2500 return $termsArray;
2501 }
2502
2503 /**
2504 * Get the first character of a string.
2505 *
2506 * @param $s string
2507 * @return string
2508 */
2509 function firstChar( $s ) {
2510 $matches = array();
2511 preg_match(
2512 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2513 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2514 $s,
2515 $matches
2516 );
2517
2518 if ( isset( $matches[1] ) ) {
2519 if ( strlen( $matches[1] ) != 3 ) {
2520 return $matches[1];
2521 }
2522
2523 // Break down Hangul syllables to grab the first jamo
2524 $code = utf8ToCodepoint( $matches[1] );
2525 if ( $code < 0xac00 || 0xd7a4 <= $code ) {
2526 return $matches[1];
2527 } elseif ( $code < 0xb098 ) {
2528 return "\xe3\x84\xb1";
2529 } elseif ( $code < 0xb2e4 ) {
2530 return "\xe3\x84\xb4";
2531 } elseif ( $code < 0xb77c ) {
2532 return "\xe3\x84\xb7";
2533 } elseif ( $code < 0xb9c8 ) {
2534 return "\xe3\x84\xb9";
2535 } elseif ( $code < 0xbc14 ) {
2536 return "\xe3\x85\x81";
2537 } elseif ( $code < 0xc0ac ) {
2538 return "\xe3\x85\x82";
2539 } elseif ( $code < 0xc544 ) {
2540 return "\xe3\x85\x85";
2541 } elseif ( $code < 0xc790 ) {
2542 return "\xe3\x85\x87";
2543 } elseif ( $code < 0xcc28 ) {
2544 return "\xe3\x85\x88";
2545 } elseif ( $code < 0xce74 ) {
2546 return "\xe3\x85\x8a";
2547 } elseif ( $code < 0xd0c0 ) {
2548 return "\xe3\x85\x8b";
2549 } elseif ( $code < 0xd30c ) {
2550 return "\xe3\x85\x8c";
2551 } elseif ( $code < 0xd558 ) {
2552 return "\xe3\x85\x8d";
2553 } else {
2554 return "\xe3\x85\x8e";
2555 }
2556 } else {
2557 return '';
2558 }
2559 }
2560
2561 function initEncoding() {
2562 # Some languages may have an alternate char encoding option
2563 # (Esperanto X-coding, Japanese furigana conversion, etc)
2564 # If this language is used as the primary content language,
2565 # an override to the defaults can be set here on startup.
2566 }
2567
2568 /**
2569 * @param $s string
2570 * @return string
2571 */
2572 function recodeForEdit( $s ) {
2573 # For some languages we'll want to explicitly specify
2574 # which characters make it into the edit box raw
2575 # or are converted in some way or another.
2576 global $wgEditEncoding;
2577 if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
2578 return $s;
2579 } else {
2580 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2581 }
2582 }
2583
2584 /**
2585 * @param $s string
2586 * @return string
2587 */
2588 function recodeInput( $s ) {
2589 # Take the previous into account.
2590 global $wgEditEncoding;
2591 if ( $wgEditEncoding != '' ) {
2592 $enc = $wgEditEncoding;
2593 } else {
2594 $enc = 'UTF-8';
2595 }
2596 if ( $enc == 'UTF-8' ) {
2597 return $s;
2598 } else {
2599 return $this->iconv( $enc, 'UTF-8', $s );
2600 }
2601 }
2602
2603 /**
2604 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2605 * also cleans up certain backwards-compatible sequences, converting them
2606 * to the modern Unicode equivalent.
2607 *
2608 * This is language-specific for performance reasons only.
2609 *
2610 * @param $s string
2611 *
2612 * @return string
2613 */
2614 function normalize( $s ) {
2615 global $wgAllUnicodeFixes;
2616 $s = UtfNormal::cleanUp( $s );
2617 if ( $wgAllUnicodeFixes ) {
2618 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2619 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2620 }
2621
2622 return $s;
2623 }
2624
2625 /**
2626 * Transform a string using serialized data stored in the given file (which
2627 * must be in the serialized subdirectory of $IP). The file contains pairs
2628 * mapping source characters to destination characters.
2629 *
2630 * The data is cached in process memory. This will go faster if you have the
2631 * FastStringSearch extension.
2632 *
2633 * @param $file string
2634 * @param $string string
2635 *
2636 * @throws MWException
2637 * @return string
2638 */
2639 function transformUsingPairFile( $file, $string ) {
2640 if ( !isset( $this->transformData[$file] ) ) {
2641 $data = wfGetPrecompiledData( $file );
2642 if ( $data === false ) {
2643 throw new MWException( __METHOD__ . ": The transformation file $file is missing" );
2644 }
2645 $this->transformData[$file] = new ReplacementArray( $data );
2646 }
2647 return $this->transformData[$file]->replace( $string );
2648 }
2649
2650 /**
2651 * For right-to-left language support
2652 *
2653 * @return bool
2654 */
2655 function isRTL() {
2656 return self::$dataCache->getItem( $this->mCode, 'rtl' );
2657 }
2658
2659 /**
2660 * Return the correct HTML 'dir' attribute value for this language.
2661 * @return String
2662 */
2663 function getDir() {
2664 return $this->isRTL() ? 'rtl' : 'ltr';
2665 }
2666
2667 /**
2668 * Return 'left' or 'right' as appropriate alignment for line-start
2669 * for this language's text direction.
2670 *
2671 * Should be equivalent to CSS3 'start' text-align value....
2672 *
2673 * @return String
2674 */
2675 function alignStart() {
2676 return $this->isRTL() ? 'right' : 'left';
2677 }
2678
2679 /**
2680 * Return 'right' or 'left' as appropriate alignment for line-end
2681 * for this language's text direction.
2682 *
2683 * Should be equivalent to CSS3 'end' text-align value....
2684 *
2685 * @return String
2686 */
2687 function alignEnd() {
2688 return $this->isRTL() ? 'left' : 'right';
2689 }
2690
2691 /**
2692 * A hidden direction mark (LRM or RLM), depending on the language direction.
2693 * Unlike getDirMark(), this function returns the character as an HTML entity.
2694 * This function should be used when the output is guaranteed to be HTML,
2695 * because it makes the output HTML source code more readable. When
2696 * the output is plain text or can be escaped, getDirMark() should be used.
2697 *
2698 * @param $opposite Boolean Get the direction mark opposite to your language
2699 * @return string
2700 */
2701 function getDirMarkEntity( $opposite = false ) {
2702 if ( $opposite ) { return $this->isRTL() ? '&lrm;' : '&rlm;'; }
2703 return $this->isRTL() ? '&rlm;' : '&lrm;';
2704 }
2705
2706 /**
2707 * A hidden direction mark (LRM or RLM), depending on the language direction.
2708 * This function produces them as invisible Unicode characters and
2709 * the output may be hard to read and debug, so it should only be used
2710 * when the output is plain text or can be escaped. When the output is
2711 * HTML, use getDirMarkEntity() instead.
2712 *
2713 * @param $opposite Boolean Get the direction mark opposite to your language
2714 * @return string
2715 */
2716 function getDirMark( $opposite = false ) {
2717 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2718 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2719 if ( $opposite ) { return $this->isRTL() ? $lrm : $rlm; }
2720 return $this->isRTL() ? $rlm : $lrm;
2721 }
2722
2723 /**
2724 * @return array
2725 */
2726 function capitalizeAllNouns() {
2727 return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
2728 }
2729
2730 /**
2731 * An arrow, depending on the language direction.
2732 *
2733 * @param $direction String: the direction of the arrow: forwards (default), backwards, left, right, up, down.
2734 * @return string
2735 */
2736 function getArrow( $direction = 'forwards' ) {
2737 switch ( $direction ) {
2738 case 'forwards':
2739 return $this->isRTL() ? '←' : '→';
2740 case 'backwards':
2741 return $this->isRTL() ? '→' : '←';
2742 case 'left':
2743 return '←';
2744 case 'right':
2745 return '→';
2746 case 'up':
2747 return '↑';
2748 case 'down':
2749 return '↓';
2750 }
2751 }
2752
2753 /**
2754 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2755 *
2756 * @return bool
2757 */
2758 function linkPrefixExtension() {
2759 return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
2760 }
2761
2762 /**
2763 * @return array
2764 */
2765 function getMagicWords() {
2766 return self::$dataCache->getItem( $this->mCode, 'magicWords' );
2767 }
2768
2769 protected function doMagicHook() {
2770 if ( $this->mMagicHookDone ) {
2771 return;
2772 }
2773 $this->mMagicHookDone = true;
2774 wfProfileIn( 'LanguageGetMagic' );
2775 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
2776 wfProfileOut( 'LanguageGetMagic' );
2777 }
2778
2779 /**
2780 * Fill a MagicWord object with data from here
2781 *
2782 * @param $mw
2783 */
2784 function getMagic( $mw ) {
2785 $this->doMagicHook();
2786
2787 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
2788 $rawEntry = $this->mMagicExtensions[$mw->mId];
2789 } else {
2790 $magicWords = $this->getMagicWords();
2791 if ( isset( $magicWords[$mw->mId] ) ) {
2792 $rawEntry = $magicWords[$mw->mId];
2793 } else {
2794 $rawEntry = false;
2795 }
2796 }
2797
2798 if ( !is_array( $rawEntry ) ) {
2799 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2800 } else {
2801 $mw->mCaseSensitive = $rawEntry[0];
2802 $mw->mSynonyms = array_slice( $rawEntry, 1 );
2803 }
2804 }
2805
2806 /**
2807 * Add magic words to the extension array
2808 *
2809 * @param $newWords array
2810 */
2811 function addMagicWordsByLang( $newWords ) {
2812 $fallbackChain = $this->getFallbackLanguages();
2813 $fallbackChain = array_reverse( $fallbackChain );
2814 foreach ( $fallbackChain as $code ) {
2815 if ( isset( $newWords[$code] ) ) {
2816 $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
2817 }
2818 }
2819 }
2820
2821 /**
2822 * Get special page names, as an associative array
2823 * case folded alias => real name
2824 */
2825 function getSpecialPageAliases() {
2826 // Cache aliases because it may be slow to load them
2827 if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
2828 // Initialise array
2829 $this->mExtendedSpecialPageAliases =
2830 self::$dataCache->getItem( $this->mCode, 'specialPageAliases' );
2831 wfRunHooks( 'LanguageGetSpecialPageAliases',
2832 array( &$this->mExtendedSpecialPageAliases, $this->getCode() ) );
2833 }
2834
2835 return $this->mExtendedSpecialPageAliases;
2836 }
2837
2838 /**
2839 * Italic is unsuitable for some languages
2840 *
2841 * @param $text String: the text to be emphasized.
2842 * @return string
2843 */
2844 function emphasize( $text ) {
2845 return "<em>$text</em>";
2846 }
2847
2848 /**
2849 * Normally we output all numbers in plain en_US style, that is
2850 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2851 * point twohundredthirtyfive. However this is not suitable for all
2852 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2853 * Icelandic just want to use commas instead of dots, and dots instead
2854 * of commas like "293.291,235".
2855 *
2856 * An example of this function being called:
2857 * <code>
2858 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2859 * </code>
2860 *
2861 * See LanguageGu.php for the Gujarati implementation and
2862 * $separatorTransformTable on MessageIs.php for
2863 * the , => . and . => , implementation.
2864 *
2865 * @todo check if it's viable to use localeconv() for the decimal
2866 * separator thing.
2867 * @param $number Mixed: the string to be formatted, should be an integer
2868 * or a floating point number.
2869 * @param $nocommafy Bool: set to true for special numbers like dates
2870 * @return string
2871 */
2872 public function formatNum( $number, $nocommafy = false ) {
2873 global $wgTranslateNumerals;
2874 if ( !$nocommafy ) {
2875 $number = $this->commafy( $number );
2876 $s = $this->separatorTransformTable();
2877 if ( $s ) {
2878 $number = strtr( $number, $s );
2879 }
2880 }
2881
2882 if ( $wgTranslateNumerals ) {
2883 $s = $this->digitTransformTable();
2884 if ( $s ) {
2885 $number = strtr( $number, $s );
2886 }
2887 }
2888
2889 return $number;
2890 }
2891
2892 /**
2893 * @param $number string
2894 * @return string
2895 */
2896 function parseFormattedNumber( $number ) {
2897 $s = $this->digitTransformTable();
2898 if ( $s ) {
2899 $number = strtr( $number, array_flip( $s ) );
2900 }
2901
2902 $s = $this->separatorTransformTable();
2903 if ( $s ) {
2904 $number = strtr( $number, array_flip( $s ) );
2905 }
2906
2907 $number = strtr( $number, array( ',' => '' ) );
2908 return $number;
2909 }
2910
2911 /**
2912 * Adds commas to a given number
2913 * @since 1.19
2914 * @param $_ mixed
2915 * @return string
2916 */
2917 function commafy( $_ ) {
2918 $digitGroupingPattern = $this->digitGroupingPattern();
2919 if ( $_ === null ) {
2920 return '';
2921 }
2922
2923 if ( !$digitGroupingPattern || $digitGroupingPattern === "###,###,###" ) {
2924 // default grouping is at thousands, use the same for ###,###,### pattern too.
2925 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2926 } else {
2927 // Ref: http://cldr.unicode.org/translation/number-patterns
2928 $sign = "";
2929 if ( intval( $_ ) < 0 ) {
2930 // For negative numbers apply the algorithm like positive number and add sign.
2931 $sign = "-";
2932 $_ = substr( $_, 1 );
2933 }
2934 $numberpart = array();
2935 $decimalpart = array();
2936 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
2937 preg_match( "/\d+/", $_, $numberpart );
2938 preg_match( "/\.\d*/", $_, $decimalpart );
2939 $groupedNumber = ( count( $decimalpart ) > 0 ) ? $decimalpart[0]:"";
2940 if ( $groupedNumber === $_ ) {
2941 // the string does not have any number part. Eg: .12345
2942 return $sign . $groupedNumber;
2943 }
2944 $start = $end = strlen( $numberpart[0] );
2945 while ( $start > 0 ) {
2946 $match = $matches[0][$numMatches -1] ;
2947 $matchLen = strlen( $match );
2948 $start = $end - $matchLen;
2949 if ( $start < 0 ) {
2950 $start = 0;
2951 }
2952 $groupedNumber = substr( $_ , $start, $end -$start ) . $groupedNumber ;
2953 $end = $start;
2954 if ( $numMatches > 1 ) {
2955 // use the last pattern for the rest of the number
2956 $numMatches--;
2957 }
2958 if ( $start > 0 ) {
2959 $groupedNumber = "," . $groupedNumber;
2960 }
2961 }
2962 return $sign . $groupedNumber;
2963 }
2964 }
2965 /**
2966 * @return String
2967 */
2968 function digitGroupingPattern() {
2969 return self::$dataCache->getItem( $this->mCode, 'digitGroupingPattern' );
2970 }
2971
2972 /**
2973 * @return array
2974 */
2975 function digitTransformTable() {
2976 return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
2977 }
2978
2979 /**
2980 * @return array
2981 */
2982 function separatorTransformTable() {
2983 return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
2984 }
2985
2986 /**
2987 * Take a list of strings and build a locale-friendly comma-separated
2988 * list, using the local comma-separator message.
2989 * The last two strings are chained with an "and".
2990 *
2991 * @param $l Array
2992 * @return string
2993 */
2994 function listToText( array $l ) {
2995 $s = '';
2996 $m = count( $l ) - 1;
2997 if ( $m == 1 ) {
2998 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2999 } else {
3000 for ( $i = $m; $i >= 0; $i-- ) {
3001 if ( $i == $m ) {
3002 $s = $l[$i];
3003 } elseif ( $i == $m - 1 ) {
3004 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
3005 } else {
3006 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
3007 }
3008 }
3009 return $s;
3010 }
3011 }
3012
3013 /**
3014 * Take a list of strings and build a locale-friendly comma-separated
3015 * list, using the local comma-separator message.
3016 * @param $list array of strings to put in a comma list
3017 * @return string
3018 */
3019 function commaList( array $list ) {
3020 return implode(
3021 wfMsgExt(
3022 'comma-separator',
3023 array( 'parsemag', 'escapenoentities', 'language' => $this )
3024 ),
3025 $list
3026 );
3027 }
3028
3029 /**
3030 * Take a list of strings and build a locale-friendly semicolon-separated
3031 * list, using the local semicolon-separator message.
3032 * @param $list array of strings to put in a semicolon list
3033 * @return string
3034 */
3035 function semicolonList( array $list ) {
3036 return implode(
3037 wfMsgExt(
3038 'semicolon-separator',
3039 array( 'parsemag', 'escapenoentities', 'language' => $this )
3040 ),
3041 $list
3042 );
3043 }
3044
3045 /**
3046 * Same as commaList, but separate it with the pipe instead.
3047 * @param $list array of strings to put in a pipe list
3048 * @return string
3049 */
3050 function pipeList( array $list ) {
3051 return implode(
3052 wfMsgExt(
3053 'pipe-separator',
3054 array( 'escapenoentities', 'language' => $this )
3055 ),
3056 $list
3057 );
3058 }
3059
3060 /**
3061 * Truncate a string to a specified length in bytes, appending an optional
3062 * string (e.g. for ellipses)
3063 *
3064 * The database offers limited byte lengths for some columns in the database;
3065 * multi-byte character sets mean we need to ensure that only whole characters
3066 * are included, otherwise broken characters can be passed to the user
3067 *
3068 * If $length is negative, the string will be truncated from the beginning
3069 *
3070 * @param $string String to truncate
3071 * @param $length Int: maximum length (including ellipses)
3072 * @param $ellipsis String to append to the truncated text
3073 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
3074 * $adjustLength was introduced in 1.18, before that behaved as if false.
3075 * @return string
3076 */
3077 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3078 # Use the localized ellipsis character
3079 if ( $ellipsis == '...' ) {
3080 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
3081 }
3082 # Check if there is no need to truncate
3083 if ( $length == 0 ) {
3084 return $ellipsis; // convention
3085 } elseif ( strlen( $string ) <= abs( $length ) ) {
3086 return $string; // no need to truncate
3087 }
3088 $stringOriginal = $string;
3089 # If ellipsis length is >= $length then we can't apply $adjustLength
3090 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3091 $string = $ellipsis; // this can be slightly unexpected
3092 # Otherwise, truncate and add ellipsis...
3093 } else {
3094 $eLength = $adjustLength ? strlen( $ellipsis ) : 0;
3095 if ( $length > 0 ) {
3096 $length -= $eLength;
3097 $string = substr( $string, 0, $length ); // xyz...
3098 $string = $this->removeBadCharLast( $string );
3099 $string = $string . $ellipsis;
3100 } else {
3101 $length += $eLength;
3102 $string = substr( $string, $length ); // ...xyz
3103 $string = $this->removeBadCharFirst( $string );
3104 $string = $ellipsis . $string;
3105 }
3106 }
3107 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3108 # This check is *not* redundant if $adjustLength, due to the single case where
3109 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3110 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3111 return $string;
3112 } else {
3113 return $stringOriginal;
3114 }
3115 }
3116
3117 /**
3118 * Remove bytes that represent an incomplete Unicode character
3119 * at the end of string (e.g. bytes of the char are missing)
3120 *
3121 * @param $string String
3122 * @return string
3123 */
3124 protected function removeBadCharLast( $string ) {
3125 if ( $string != '' ) {
3126 $char = ord( $string[strlen( $string ) - 1] );
3127 $m = array();
3128 if ( $char >= 0xc0 ) {
3129 # We got the first byte only of a multibyte char; remove it.
3130 $string = substr( $string, 0, -1 );
3131 } elseif ( $char >= 0x80 &&
3132 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3133 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
3134 {
3135 # We chopped in the middle of a character; remove it
3136 $string = $m[1];
3137 }
3138 }
3139 return $string;
3140 }
3141
3142 /**
3143 * Remove bytes that represent an incomplete Unicode character
3144 * at the start of string (e.g. bytes of the char are missing)
3145 *
3146 * @param $string String
3147 * @return string
3148 */
3149 protected function removeBadCharFirst( $string ) {
3150 if ( $string != '' ) {
3151 $char = ord( $string[0] );
3152 if ( $char >= 0x80 && $char < 0xc0 ) {
3153 # We chopped in the middle of a character; remove the whole thing
3154 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3155 }
3156 }
3157 return $string;
3158 }
3159
3160 /**
3161 * Truncate a string of valid HTML to a specified length in bytes,
3162 * appending an optional string (e.g. for ellipses), and return valid HTML
3163 *
3164 * This is only intended for styled/linked text, such as HTML with
3165 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3166 * Also, this will not detect things like "display:none" CSS.
3167 *
3168 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3169 *
3170 * @param string $text HTML string to truncate
3171 * @param int $length (zero/positive) Maximum length (including ellipses)
3172 * @param string $ellipsis String to append to the truncated text
3173 * @return string
3174 */
3175 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3176 # Use the localized ellipsis character
3177 if ( $ellipsis == '...' ) {
3178 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
3179 }
3180 # Check if there is clearly no need to truncate
3181 if ( $length <= 0 ) {
3182 return $ellipsis; // no text shown, nothing to format (convention)
3183 } elseif ( strlen( $text ) <= $length ) {
3184 return $text; // string short enough even *with* HTML (short-circuit)
3185 }
3186
3187 $dispLen = 0; // innerHTML legth so far
3188 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3189 $tagType = 0; // 0-open, 1-close
3190 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3191 $entityState = 0; // 0-not entity, 1-entity
3192 $tag = $ret = ''; // accumulated tag name, accumulated result string
3193 $openTags = array(); // open tag stack
3194 $maybeState = null; // possible truncation state
3195
3196 $textLen = strlen( $text );
3197 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3198 for ( $pos = 0; true; ++$pos ) {
3199 # Consider truncation once the display length has reached the maximim.
3200 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3201 # Check that we're not in the middle of a bracket/entity...
3202 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3203 if ( !$testingEllipsis ) {
3204 $testingEllipsis = true;
3205 # Save where we are; we will truncate here unless there turn out to
3206 # be so few remaining characters that truncation is not necessary.
3207 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3208 $maybeState = array( $ret, $openTags ); // save state
3209 }
3210 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3211 # String in fact does need truncation, the truncation point was OK.
3212 list( $ret, $openTags ) = $maybeState; // reload state
3213 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3214 $ret .= $ellipsis; // add ellipsis
3215 break;
3216 }
3217 }
3218 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3219
3220 # Read the next char...
3221 $ch = $text[$pos];
3222 $lastCh = $pos ? $text[$pos - 1] : '';
3223 $ret .= $ch; // add to result string
3224 if ( $ch == '<' ) {
3225 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3226 $entityState = 0; // for bad HTML
3227 $bracketState = 1; // tag started (checking for backslash)
3228 } elseif ( $ch == '>' ) {
3229 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3230 $entityState = 0; // for bad HTML
3231 $bracketState = 0; // out of brackets
3232 } elseif ( $bracketState == 1 ) {
3233 if ( $ch == '/' ) {
3234 $tagType = 1; // close tag (e.g. "</span>")
3235 } else {
3236 $tagType = 0; // open tag (e.g. "<span>")
3237 $tag .= $ch;
3238 }
3239 $bracketState = 2; // building tag name
3240 } elseif ( $bracketState == 2 ) {
3241 if ( $ch != ' ' ) {
3242 $tag .= $ch;
3243 } else {
3244 // Name found (e.g. "<a href=..."), add on tag attributes...
3245 $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
3246 }
3247 } elseif ( $bracketState == 0 ) {
3248 if ( $entityState ) {
3249 if ( $ch == ';' ) {
3250 $entityState = 0;
3251 $dispLen++; // entity is one displayed char
3252 }
3253 } else {
3254 if ( $neLength == 0 && !$maybeState ) {
3255 // Save state without $ch. We want to *hit* the first
3256 // display char (to get tags) but not *use* it if truncating.
3257 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3258 }
3259 if ( $ch == '&' ) {
3260 $entityState = 1; // entity found, (e.g. "&#160;")
3261 } else {
3262 $dispLen++; // this char is displayed
3263 // Add the next $max display text chars after this in one swoop...
3264 $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
3265 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
3266 $dispLen += $skipped;
3267 $pos += $skipped;
3268 }
3269 }
3270 }
3271 }
3272 // Close the last tag if left unclosed by bad HTML
3273 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3274 while ( count( $openTags ) > 0 ) {
3275 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3276 }
3277 return $ret;
3278 }
3279
3280 /**
3281 * truncateHtml() helper function
3282 * like strcspn() but adds the skipped chars to $ret
3283 *
3284 * @param $ret
3285 * @param $text
3286 * @param $search
3287 * @param $start
3288 * @param $len
3289 * @return int
3290 */
3291 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3292 if ( $len === null ) {
3293 $len = -1; // -1 means "no limit" for strcspn
3294 } elseif ( $len < 0 ) {
3295 $len = 0; // sanity
3296 }
3297 $skipCount = 0;
3298 if ( $start < strlen( $text ) ) {
3299 $skipCount = strcspn( $text, $search, $start, $len );
3300 $ret .= substr( $text, $start, $skipCount );
3301 }
3302 return $skipCount;
3303 }
3304
3305 /**
3306 * truncateHtml() helper function
3307 * (a) push or pop $tag from $openTags as needed
3308 * (b) clear $tag value
3309 * @param &$tag string Current HTML tag name we are looking at
3310 * @param $tagType int (0-open tag, 1-close tag)
3311 * @param $lastCh string Character before the '>' that ended this tag
3312 * @param &$openTags array Open tag stack (not accounting for $tag)
3313 */
3314 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3315 $tag = ltrim( $tag );
3316 if ( $tag != '' ) {
3317 if ( $tagType == 0 && $lastCh != '/' ) {
3318 $openTags[] = $tag; // tag opened (didn't close itself)
3319 } elseif ( $tagType == 1 ) {
3320 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3321 array_pop( $openTags ); // tag closed
3322 }
3323 }
3324 $tag = '';
3325 }
3326 }
3327
3328 /**
3329 * Grammatical transformations, needed for inflected languages
3330 * Invoked by putting {{grammar:case|word}} in a message
3331 *
3332 * @param $word string
3333 * @param $case string
3334 * @return string
3335 */
3336 function convertGrammar( $word, $case ) {
3337 global $wgGrammarForms;
3338 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3339 return $wgGrammarForms[$this->getCode()][$case][$word];
3340 }
3341 return $word;
3342 }
3343 /**
3344 * Get the grammar forms for the content language
3345 * @return array of grammar forms
3346 * @since 1.20
3347 */
3348 function getGrammarForms() {
3349 global $wgGrammarForms;
3350 if ( isset( $wgGrammarForms[$this->getCode()] ) && is_array( $wgGrammarForms[$this->getCode()] ) ) {
3351 return $wgGrammarForms[$this->getCode()];
3352 }
3353 return array();
3354 }
3355 /**
3356 * Provides an alternative text depending on specified gender.
3357 * Usage {{gender:username|masculine|feminine|neutral}}.
3358 * username is optional, in which case the gender of current user is used,
3359 * but only in (some) interface messages; otherwise default gender is used.
3360 *
3361 * If no forms are given, an empty string is returned. If only one form is
3362 * given, it will be returned unconditionally. These details are implied by
3363 * the caller and cannot be overridden in subclasses.
3364 *
3365 * If more than one form is given, the default is to use the neutral one
3366 * if it is specified, and to use the masculine one otherwise. These
3367 * details can be overridden in subclasses.
3368 *
3369 * @param $gender string
3370 * @param $forms array
3371 *
3372 * @return string
3373 */
3374 function gender( $gender, $forms ) {
3375 if ( !count( $forms ) ) {
3376 return '';
3377 }
3378 $forms = $this->preConvertPlural( $forms, 2 );
3379 if ( $gender === 'male' ) {
3380 return $forms[0];
3381 }
3382 if ( $gender === 'female' ) {
3383 return $forms[1];
3384 }
3385 return isset( $forms[2] ) ? $forms[2] : $forms[0];
3386 }
3387
3388 /**
3389 * Plural form transformations, needed for some languages.
3390 * For example, there are 3 form of plural in Russian and Polish,
3391 * depending on "count mod 10". See [[w:Plural]]
3392 * For English it is pretty simple.
3393 *
3394 * Invoked by putting {{plural:count|wordform1|wordform2}}
3395 * or {{plural:count|wordform1|wordform2|wordform3}}
3396 *
3397 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3398 *
3399 * @param $count Integer: non-localized number
3400 * @param $forms Array: different plural forms
3401 * @return string Correct form of plural for $count in this language
3402 */
3403 function convertPlural( $count, $forms ) {
3404 if ( !count( $forms ) ) {
3405 return '';
3406 }
3407 $forms = $this->preConvertPlural( $forms, 2 );
3408
3409 return ( $count == 1 ) ? $forms[0] : $forms[1];
3410 }
3411
3412 /**
3413 * Checks that convertPlural was given an array and pads it to requested
3414 * amount of forms by copying the last one.
3415 *
3416 * @param $count Integer: How many forms should there be at least
3417 * @param $forms Array of forms given to convertPlural
3418 * @return array Padded array of forms or an exception if not an array
3419 */
3420 protected function preConvertPlural( /* Array */ $forms, $count ) {
3421 while ( count( $forms ) < $count ) {
3422 $forms[] = $forms[count( $forms ) - 1];
3423 }
3424 return $forms;
3425 }
3426
3427 /**
3428 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3429 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3430 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3431 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3432 * match up with it.
3433 *
3434 * @param $str String: the validated block duration in English
3435 * @return string Somehow translated block duration
3436 * @see LanguageFi.php for example implementation
3437 */
3438 function translateBlockExpiry( $str ) {
3439 $duration = SpecialBlock::getSuggestedDurations( $this );
3440 foreach ( $duration as $show => $value ) {
3441 if ( strcmp( $str, $value ) == 0 ) {
3442 return htmlspecialchars( trim( $show ) );
3443 }
3444 }
3445
3446 // Since usually only infinite or indefinite is only on list, so try
3447 // equivalents if still here.
3448 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3449 if ( in_array( $str, $indefs ) ) {
3450 foreach ( $indefs as $val ) {
3451 $show = array_search( $val, $duration, true );
3452 if ( $show !== false ) {
3453 return htmlspecialchars( trim( $show ) );
3454 }
3455 }
3456 }
3457 // If all else fails, return the original string.
3458 return $str;
3459 }
3460
3461 /**
3462 * languages like Chinese need to be segmented in order for the diff
3463 * to be of any use
3464 *
3465 * @param $text String
3466 * @return String
3467 */
3468 public function segmentForDiff( $text ) {
3469 return $text;
3470 }
3471
3472 /**
3473 * and unsegment to show the result
3474 *
3475 * @param $text String
3476 * @return String
3477 */
3478 public function unsegmentForDiff( $text ) {
3479 return $text;
3480 }
3481
3482 /**
3483 * Return the LanguageConverter used in the Language
3484 *
3485 * @since 1.19
3486 * @return LanguageConverter
3487 */
3488 public function getConverter() {
3489 return $this->mConverter;
3490 }
3491
3492 /**
3493 * convert text to all supported variants
3494 *
3495 * @param $text string
3496 * @return array
3497 */
3498 public function autoConvertToAllVariants( $text ) {
3499 return $this->mConverter->autoConvertToAllVariants( $text );
3500 }
3501
3502 /**
3503 * convert text to different variants of a language.
3504 *
3505 * @param $text string
3506 * @return string
3507 */
3508 public function convert( $text ) {
3509 return $this->mConverter->convert( $text );
3510 }
3511
3512 /**
3513 * Convert a Title object to a string in the preferred variant
3514 *
3515 * @param $title Title
3516 * @return string
3517 */
3518 public function convertTitle( $title ) {
3519 return $this->mConverter->convertTitle( $title );
3520 }
3521
3522 /**
3523 * Check if this is a language with variants
3524 *
3525 * @return bool
3526 */
3527 public function hasVariants() {
3528 return sizeof( $this->getVariants() ) > 1;
3529 }
3530
3531 /**
3532 * Check if the language has the specific variant
3533 *
3534 * @since 1.19
3535 * @param $variant string
3536 * @return bool
3537 */
3538 public function hasVariant( $variant ) {
3539 return (bool)$this->mConverter->validateVariant( $variant );
3540 }
3541
3542 /**
3543 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3544 *
3545 * @param $text string
3546 * @return string
3547 */
3548 public function armourMath( $text ) {
3549 return $this->mConverter->armourMath( $text );
3550 }
3551
3552 /**
3553 * Perform output conversion on a string, and encode for safe HTML output.
3554 * @param $text String text to be converted
3555 * @param $isTitle Bool whether this conversion is for the article title
3556 * @return string
3557 * @todo this should get integrated somewhere sane
3558 */
3559 public function convertHtml( $text, $isTitle = false ) {
3560 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3561 }
3562
3563 /**
3564 * @param $key string
3565 * @return string
3566 */
3567 public function convertCategoryKey( $key ) {
3568 return $this->mConverter->convertCategoryKey( $key );
3569 }
3570
3571 /**
3572 * Get the list of variants supported by this language
3573 * see sample implementation in LanguageZh.php
3574 *
3575 * @return array an array of language codes
3576 */
3577 public function getVariants() {
3578 return $this->mConverter->getVariants();
3579 }
3580
3581 /**
3582 * @return string
3583 */
3584 public function getPreferredVariant() {
3585 return $this->mConverter->getPreferredVariant();
3586 }
3587
3588 /**
3589 * @return string
3590 */
3591 public function getDefaultVariant() {
3592 return $this->mConverter->getDefaultVariant();
3593 }
3594
3595 /**
3596 * @return string
3597 */
3598 public function getURLVariant() {
3599 return $this->mConverter->getURLVariant();
3600 }
3601
3602 /**
3603 * If a language supports multiple variants, it is
3604 * possible that non-existing link in one variant
3605 * actually exists in another variant. this function
3606 * tries to find it. See e.g. LanguageZh.php
3607 *
3608 * @param $link String: the name of the link
3609 * @param $nt Mixed: the title object of the link
3610 * @param $ignoreOtherCond Boolean: to disable other conditions when
3611 * we need to transclude a template or update a category's link
3612 * @return null the input parameters may be modified upon return
3613 */
3614 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3615 $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
3616 }
3617
3618 /**
3619 * If a language supports multiple variants, converts text
3620 * into an array of all possible variants of the text:
3621 * 'variant' => text in that variant
3622 *
3623 * @deprecated since 1.17 Use autoConvertToAllVariants()
3624 *
3625 * @param $text string
3626 *
3627 * @return string
3628 */
3629 public function convertLinkToAllVariants( $text ) {
3630 return $this->mConverter->convertLinkToAllVariants( $text );
3631 }
3632
3633 /**
3634 * returns language specific options used by User::getPageRenderHash()
3635 * for example, the preferred language variant
3636 *
3637 * @return string
3638 */
3639 function getExtraHashOptions() {
3640 return $this->mConverter->getExtraHashOptions();
3641 }
3642
3643 /**
3644 * For languages that support multiple variants, the title of an
3645 * article may be displayed differently in different variants. this
3646 * function returns the apporiate title defined in the body of the article.
3647 *
3648 * @return string
3649 */
3650 public function getParsedTitle() {
3651 return $this->mConverter->getParsedTitle();
3652 }
3653
3654 /**
3655 * Enclose a string with the "no conversion" tag. This is used by
3656 * various functions in the Parser
3657 *
3658 * @param $text String: text to be tagged for no conversion
3659 * @param $noParse bool
3660 * @return string the tagged text
3661 */
3662 public function markNoConversion( $text, $noParse = false ) {
3663 return $this->mConverter->markNoConversion( $text, $noParse );
3664 }
3665
3666 /**
3667 * A regular expression to match legal word-trailing characters
3668 * which should be merged onto a link of the form [[foo]]bar.
3669 *
3670 * @return string
3671 */
3672 public function linkTrail() {
3673 return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
3674 }
3675
3676 /**
3677 * @return Language
3678 */
3679 function getLangObj() {
3680 return $this;
3681 }
3682
3683 /**
3684 * Get the RFC 3066 code for this language object
3685 *
3686 * @return string
3687 */
3688 public function getCode() {
3689 return $this->mCode;
3690 }
3691
3692 /**
3693 * Get the code in Bcp47 format which we can use
3694 * inside of html lang="" tags.
3695 * @since 1.19
3696 * @return string
3697 */
3698 public function getHtmlCode() {
3699 if ( is_null( $this->mHtmlCode ) ) {
3700 $this->mHtmlCode = wfBCP47( $this->getCode() );
3701 }
3702 return $this->mHtmlCode;
3703 }
3704
3705 /**
3706 * @param $code string
3707 */
3708 public function setCode( $code ) {
3709 $this->mCode = $code;
3710 // Ensure we don't leave an incorrect html code lying around
3711 $this->mHtmlCode = null;
3712 }
3713
3714 /**
3715 * Get the name of a file for a certain language code
3716 * @param $prefix string Prepend this to the filename
3717 * @param $code string Language code
3718 * @param $suffix string Append this to the filename
3719 * @throws MWException
3720 * @return string $prefix . $mangledCode . $suffix
3721 */
3722 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3723 // Protect against path traversal
3724 if ( !Language::isValidCode( $code )
3725 || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3726 {
3727 throw new MWException( "Invalid language code \"$code\"" );
3728 }
3729
3730 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3731 }
3732
3733 /**
3734 * Get the language code from a file name. Inverse of getFileName()
3735 * @param $filename string $prefix . $languageCode . $suffix
3736 * @param $prefix string Prefix before the language code
3737 * @param $suffix string Suffix after the language code
3738 * @return string Language code, or false if $prefix or $suffix isn't found
3739 */
3740 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3741 $m = null;
3742 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3743 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3744 if ( !count( $m ) ) {
3745 return false;
3746 }
3747 return str_replace( '_', '-', strtolower( $m[1] ) );
3748 }
3749
3750 /**
3751 * @param $code string
3752 * @return string
3753 */
3754 public static function getMessagesFileName( $code ) {
3755 global $IP;
3756 $file = self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3757 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3758 return $file;
3759 }
3760
3761 /**
3762 * @param $code string
3763 * @return string
3764 */
3765 public static function getClassFileName( $code ) {
3766 global $IP;
3767 return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3768 }
3769
3770 /**
3771 * Get the first fallback for a given language.
3772 *
3773 * @param $code string
3774 *
3775 * @return bool|string
3776 */
3777 public static function getFallbackFor( $code ) {
3778 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
3779 return false;
3780 } else {
3781 $fallbacks = self::getFallbacksFor( $code );
3782 $first = array_shift( $fallbacks );
3783 return $first;
3784 }
3785 }
3786
3787 /**
3788 * Get the ordered list of fallback languages.
3789 *
3790 * @since 1.19
3791 * @param $code string Language code
3792 * @return array
3793 */
3794 public static function getFallbacksFor( $code ) {
3795 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
3796 return array();
3797 } else {
3798 $v = self::getLocalisationCache()->getItem( $code, 'fallback' );
3799 $v = array_map( 'trim', explode( ',', $v ) );
3800 if ( $v[count( $v ) - 1] !== 'en' ) {
3801 $v[] = 'en';
3802 }
3803 return $v;
3804 }
3805 }
3806
3807 /**
3808 * Get all messages for a given language
3809 * WARNING: this may take a long time. If you just need all message *keys*
3810 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3811 *
3812 * @param $code string
3813 *
3814 * @return array
3815 */
3816 public static function getMessagesFor( $code ) {
3817 return self::getLocalisationCache()->getItem( $code, 'messages' );
3818 }
3819
3820 /**
3821 * Get a message for a given language
3822 *
3823 * @param $key string
3824 * @param $code string
3825 *
3826 * @return string
3827 */
3828 public static function getMessageFor( $key, $code ) {
3829 return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3830 }
3831
3832 /**
3833 * Get all message keys for a given language. This is a faster alternative to
3834 * array_keys( Language::getMessagesFor( $code ) )
3835 *
3836 * @since 1.19
3837 * @param $code string Language code
3838 * @return array of message keys (strings)
3839 */
3840 public static function getMessageKeysFor( $code ) {
3841 return self::getLocalisationCache()->getSubItemList( $code, 'messages' );
3842 }
3843
3844 /**
3845 * @param $talk
3846 * @return mixed
3847 */
3848 function fixVariableInNamespace( $talk ) {
3849 if ( strpos( $talk, '$1' ) === false ) {
3850 return $talk;
3851 }
3852
3853 global $wgMetaNamespace;
3854 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3855
3856 # Allow grammar transformations
3857 # Allowing full message-style parsing would make simple requests
3858 # such as action=raw much more expensive than they need to be.
3859 # This will hopefully cover most cases.
3860 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3861 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3862 return str_replace( ' ', '_', $talk );
3863 }
3864
3865 /**
3866 * @param $m string
3867 * @return string
3868 */
3869 function replaceGrammarInNamespace( $m ) {
3870 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3871 }
3872
3873 /**
3874 * @throws MWException
3875 * @return array
3876 */
3877 static function getCaseMaps() {
3878 static $wikiUpperChars, $wikiLowerChars;
3879 if ( isset( $wikiUpperChars ) ) {
3880 return array( $wikiUpperChars, $wikiLowerChars );
3881 }
3882
3883 wfProfileIn( __METHOD__ );
3884 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3885 if ( $arr === false ) {
3886 throw new MWException(
3887 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3888 }
3889 $wikiUpperChars = $arr['wikiUpperChars'];
3890 $wikiLowerChars = $arr['wikiLowerChars'];
3891 wfProfileOut( __METHOD__ );
3892 return array( $wikiUpperChars, $wikiLowerChars );
3893 }
3894
3895 /**
3896 * Decode an expiry (block, protection, etc) which has come from the DB
3897 *
3898 * @FIXME: why are we returnings DBMS-dependent strings???
3899 *
3900 * @param $expiry String: Database expiry String
3901 * @param $format Bool|Int true to process using language functions, or TS_ constant
3902 * to return the expiry in a given timestamp
3903 * @return String
3904 */
3905 public function formatExpiry( $expiry, $format = true ) {
3906 static $infinity, $infinityMsg;
3907 if ( $infinity === null ) {
3908 $infinityMsg = wfMessage( 'infiniteblock' );
3909 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
3910 }
3911
3912 if ( $expiry == '' || $expiry == $infinity ) {
3913 return $format === true
3914 ? $infinityMsg
3915 : $infinity;
3916 } else {
3917 return $format === true
3918 ? $this->timeanddate( $expiry, /* User preference timezone */ true )
3919 : wfTimestamp( $format, $expiry );
3920 }
3921 }
3922
3923 /**
3924 * @todo Document
3925 * @param $seconds int|float
3926 * @param $format Array Optional
3927 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
3928 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
3929 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
3930 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
3931 * @return string
3932 */
3933 function formatTimePeriod( $seconds, $format = array() ) {
3934 if ( !is_array( $format ) ) {
3935 $format = array( 'avoid' => $format ); // For backwards compatibility
3936 }
3937 if ( !isset( $format['avoid'] ) ) {
3938 $format['avoid'] = false;
3939 }
3940 if ( !isset( $format['noabbrevs' ] ) ) {
3941 $format['noabbrevs'] = false;
3942 }
3943 $secondsMsg = wfMessage(
3944 $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this );
3945 $minutesMsg = wfMessage(
3946 $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this );
3947 $hoursMsg = wfMessage(
3948 $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
3949 $daysMsg = wfMessage(
3950 $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
3951
3952 if ( round( $seconds * 10 ) < 100 ) {
3953 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3954 $s = $secondsMsg->params( $s )->text();
3955 } elseif ( round( $seconds ) < 60 ) {
3956 $s = $this->formatNum( round( $seconds ) );
3957 $s = $secondsMsg->params( $s )->text();
3958 } elseif ( round( $seconds ) < 3600 ) {
3959 $minutes = floor( $seconds / 60 );
3960 $secondsPart = round( fmod( $seconds, 60 ) );
3961 if ( $secondsPart == 60 ) {
3962 $secondsPart = 0;
3963 $minutes++;
3964 }
3965 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3966 $s .= ' ';
3967 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3968 } elseif ( round( $seconds ) <= 2 * 86400 ) {
3969 $hours = floor( $seconds / 3600 );
3970 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3971 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3972 if ( $secondsPart == 60 ) {
3973 $secondsPart = 0;
3974 $minutes++;
3975 }
3976 if ( $minutes == 60 ) {
3977 $minutes = 0;
3978 $hours++;
3979 }
3980 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
3981 $s .= ' ';
3982 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3983 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
3984 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3985 }
3986 } else {
3987 $days = floor( $seconds / 86400 );
3988 if ( $format['avoid'] === 'avoidminutes' ) {
3989 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
3990 if ( $hours == 24 ) {
3991 $hours = 0;
3992 $days++;
3993 }
3994 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3995 $s .= ' ';
3996 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3997 } elseif ( $format['avoid'] === 'avoidseconds' ) {
3998 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
3999 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4000 if ( $minutes == 60 ) {
4001 $minutes = 0;
4002 $hours++;
4003 }
4004 if ( $hours == 24 ) {
4005 $hours = 0;
4006 $days++;
4007 }
4008 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4009 $s .= ' ';
4010 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4011 $s .= ' ';
4012 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4013 } else {
4014 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4015 $s .= ' ';
4016 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4017 }
4018 }
4019 return $s;
4020 }
4021
4022 /**
4023 * Format a bitrate for output, using an appropriate
4024 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
4025 *
4026 * This use base 1000. For base 1024 use formatSize(), for another base
4027 * see formatComputingNumbers()
4028 *
4029 * @param $bps int
4030 * @return string
4031 */
4032 function formatBitrate( $bps ) {
4033 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4034 }
4035
4036 /**
4037 * @param $size int Size of the unit
4038 * @param $boundary int Size boundary (1000, or 1024 in most cases)
4039 * @param $messageKey string Message key to be uesd
4040 * @return string
4041 */
4042 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4043 if ( $size <= 0 ) {
4044 return str_replace( '$1', $this->formatNum( $size ),
4045 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4046 );
4047 }
4048 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4049 $index = 0;
4050
4051 $maxIndex = count( $sizes ) - 1;
4052 while ( $size >= $boundary && $index < $maxIndex ) {
4053 $index++;
4054 $size /= $boundary;
4055 }
4056
4057 // For small sizes no decimal places necessary
4058 $round = 0;
4059 if ( $index > 1 ) {
4060 // For MB and bigger two decimal places are smarter
4061 $round = 2;
4062 }
4063 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4064
4065 $size = round( $size, $round );
4066 $text = $this->getMessageFromDB( $msg );
4067 return str_replace( '$1', $this->formatNum( $size ), $text );
4068 }
4069
4070 /**
4071 * Format a size in bytes for output, using an appropriate
4072 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4073 *
4074 * This method use base 1024. For base 1000 use formatBitrate(), for
4075 * another base see formatComputingNumbers()
4076 *
4077 * @param $size int Size to format
4078 * @return string Plain text (not HTML)
4079 */
4080 function formatSize( $size ) {
4081 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4082 }
4083
4084 /**
4085 * Make a list item, used by various special pages
4086 *
4087 * @param $page String Page link
4088 * @param $details String Text between brackets
4089 * @param $oppositedm Boolean Add the direction mark opposite to your
4090 * language, to display text properly
4091 * @return String
4092 */
4093 function specialList( $page, $details, $oppositedm = true ) {
4094 $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) .
4095 $this->getDirMark();
4096 $details = $details ? $dirmark . $this->getMessageFromDB( 'word-separator' ) .
4097 wfMsgExt( 'parentheses', array( 'escape', 'replaceafter', 'language' => $this ), $details ) : '';
4098 return $page . $details;
4099 }
4100
4101 /**
4102 * Generate (prev x| next x) (20|50|100...) type links for paging
4103 *
4104 * @param $title Title object to link
4105 * @param $offset Integer offset parameter
4106 * @param $limit Integer limit parameter
4107 * @param $query String optional URL query parameter string
4108 * @param $atend Bool optional param for specified if this is the last page
4109 * @return String
4110 */
4111 public function viewPrevNext( Title $title, $offset, $limit, array $query = array(), $atend = false ) {
4112 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4113
4114 # Make 'previous' link
4115 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4116 if ( $offset > 0 ) {
4117 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4118 $query, $prev, 'prevn-title', 'mw-prevlink' );
4119 } else {
4120 $plink = htmlspecialchars( $prev );
4121 }
4122
4123 # Make 'next' link
4124 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4125 if ( $atend ) {
4126 $nlink = htmlspecialchars( $next );
4127 } else {
4128 $nlink = $this->numLink( $title, $offset + $limit, $limit,
4129 $query, $next, 'prevn-title', 'mw-nextlink' );
4130 }
4131
4132 # Make links to set number of items per page
4133 $numLinks = array();
4134 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4135 $numLinks[] = $this->numLink( $title, $offset, $num,
4136 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4137 }
4138
4139 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4140 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4141 }
4142
4143 /**
4144 * Helper function for viewPrevNext() that generates links
4145 *
4146 * @param $title Title object to link
4147 * @param $offset Integer offset parameter
4148 * @param $limit Integer limit parameter
4149 * @param $query Array extra query parameters
4150 * @param $link String text to use for the link; will be escaped
4151 * @param $tooltipMsg String name of the message to use as tooltip
4152 * @param $class String value of the "class" attribute of the link
4153 * @return String HTML fragment
4154 */
4155 private function numLink( Title $title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4156 $query = array( 'limit' => $limit, 'offset' => $offset ) + $query;
4157 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4158 return Html::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4159 'title' => $tooltip, 'class' => $class ), $link );
4160 }
4161
4162 /**
4163 * Get the conversion rule title, if any.
4164 *
4165 * @return string
4166 */
4167 public function getConvRuleTitle() {
4168 return $this->mConverter->getConvRuleTitle();
4169 }
4170 }